<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  
  <title>个人博客</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta property="og:type" content="website">
<meta property="og:title" content="个人博客">
<meta property="og:url" content="https://gitee.com/wieldy/bailment-blog/page/3/index.html">
<meta property="og:site_name" content="个人博客">
<meta property="og:locale" content="en_US">
<meta property="article:author" content="John Doe">
<meta name="twitter:card" content="summary">
  
    <link rel="alternate" href="/bailment-blog/atom.xml" title="个人博客" type="application/atom+xml">
  
  
    <link rel="shortcut icon" href="/bailment-blog/favicon.png">
  
  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/typeface-source-code-pro@0.0.71/index.min.css">

  
  
<link rel="stylesheet" href="/bailment-blog/css/style.css">

  
    
<link rel="stylesheet" href="/bailment-blog/fancybox/jquery.fancybox.min.css">

  
<meta name="generator" content="Hexo 6.3.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/bailment-blog/" id="logo">个人博客</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/bailment-blog/">Home</a>
        
          <a class="main-nav-link" href="/bailment-blog/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/bailment-blog/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="https://gitee.com/wieldy/bailment-blog"></form>
      </div>
    </div>
  </div>
</header>

      <div class="outer">
        <section id="main">
  
    <article id="post-koa" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/bailment-blog/2022/03/29/koa/" class="article-date">
  <time class="dt-published" datetime="2022-03-29T14:12:00.000Z" itemprop="datePublished">2022-03-29</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="p-name article-title" href="/bailment-blog/2022/03/29/koa/">koa</a>
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <h2 id="express-和-koa的区别"><a href="#express-和-koa的区别" class="headerlink" title="express 和 koa的区别"></a>express 和 koa的区别</h2><ul>
<li>express 典型的是es5语法 express.Router, 内置了路由系统。 内置中间件， express.staic 对req和res进行了封装。 中间件函数的概念use， 回调嵌套的方式 </li>
<li>koa  典型的es6语法 promise来实现的， 非常小，没有多余的内容。 只有一个use方法，在使用的时候可以采用koa 去二次封装来实现</li>
</ul>
<ul>
<li><p>手写koa</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// koa/index.js</span></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = <span class="built_in">require</span>(<span class="string">&#x27;./lib/application&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// koa/lib/application.js</span></span><br><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">&#x27;http&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> context = <span class="built_in">require</span>(<span class="string">&#x27;./context&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> request = <span class="built_in">require</span>(<span class="string">&#x27;./request&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> response = <span class="built_in">require</span>(<span class="string">&#x27;./response&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> <span class="title class_">EventEmitter</span> = <span class="built_in">require</span>(<span class="string">&#x27;events&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> <span class="title class_">Stream</span> = <span class="built_in">require</span>(<span class="string">&#x27;stream&#x27;</span>);</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Application</span> <span class="keyword">extends</span> <span class="title class_ inherited__">EventEmitter</span> &#123;</span><br><span class="line">    <span class="title function_">constructor</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="variable language_">super</span>();</span><br><span class="line">        <span class="comment">// this.app = this.context;</span></span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">context</span> = <span class="title class_">Object</span>.<span class="title function_">create</span>(context); <span class="comment">// 此context是被共享的</span></span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">request</span> = <span class="title class_">Object</span>.<span class="title function_">create</span>(request);</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">response</span> = <span class="title class_">Object</span>.<span class="title function_">create</span>(response); <span class="comment">// 应用的隔离</span></span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">middlewares</span> = [];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">use</span>(<span class="params">middleware</span>) &#123;</span><br><span class="line">        <span class="comment">// this.middleware = middleware;</span></span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">middlewares</span>.<span class="title function_">push</span>(middleware);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">createContext</span>(<span class="params">req, res</span>) &#123;</span><br><span class="line">        <span class="keyword">let</span> context = <span class="title class_">Object</span>.<span class="title function_">create</span>(<span class="variable language_">this</span>.<span class="property">context</span>);</span><br><span class="line">        <span class="keyword">let</span> request = <span class="title class_">Object</span>.<span class="title function_">create</span>(<span class="variable language_">this</span>.<span class="property">request</span>);</span><br><span class="line">        <span class="keyword">let</span> response = <span class="title class_">Object</span>.<span class="title function_">create</span>(<span class="variable language_">this</span>.<span class="property">response</span>);</span><br><span class="line">        context.<span class="property">request</span> = request;</span><br><span class="line">        context.<span class="property">response</span> = response;</span><br><span class="line"></span><br><span class="line">        context.<span class="property">req</span> = context.<span class="property">request</span>.<span class="property">req</span> = req;</span><br><span class="line">        context.<span class="property">res</span> = context.<span class="property">response</span>.<span class="property">res</span> = res;</span><br><span class="line">        <span class="keyword">return</span> context</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">compose</span>(<span class="params">ctx</span>) &#123;</span><br><span class="line">        <span class="keyword">const</span> <span class="title function_">dispatch</span> = (<span class="params">i</span>) =&gt; &#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">middlewares</span>.<span class="property">length</span> === i) <span class="keyword">return</span> <span class="title class_">Promise</span>.<span class="title function_">resolve</span>();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="title class_">Promise</span>.<span class="title function_">resolve</span>(<span class="variable language_">this</span>.<span class="property">middlewares</span>[i](ctx, <span class="function">() =&gt;</span> <span class="title function_">dispatch</span>(i + <span class="number">1</span>)))</span><br><span class="line">            &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="title class_">Promise</span>.<span class="title function_">reject</span>(e)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="title function_">dispatch</span>(<span class="number">0</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    handleRequest = <span class="function">(<span class="params">req, res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">const</span> ctx = <span class="variable language_">this</span>.<span class="title function_">createContext</span>(req, res);</span><br><span class="line">        res.<span class="property">statusCode</span> = <span class="number">404</span>;</span><br><span class="line">        <span class="comment">// this.middleware(ctx); // 内部会设置body的值 </span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="variable language_">this</span>.<span class="title function_">compose</span>(ctx).<span class="title function_">then</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (ctx.<span class="property">body</span> <span class="keyword">instanceof</span> <span class="title class_">Stream</span>) &#123; <span class="comment">// 这里可以对ctx.body的类型进行判断</span></span><br><span class="line"></span><br><span class="line">                <span class="comment">// res.setHeader(&#x27;Content-Type&#x27;, &#x27;application/octet-stream&#x27;);</span></span><br><span class="line">                <span class="comment">// res.setHeader(&#x27;Content-Disposition&#x27;, &#x27;attachment;filename=2018-03-03_15-47-45--2019-0&#x27;)</span></span><br><span class="line">                ctx.<span class="property">body</span>.<span class="title function_">pipe</span>(res)</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">typeof</span> ctx.<span class="property">body</span> === <span class="string">&#x27;object&#x27;</span>) &#123;</span><br><span class="line">                ctx.<span class="property">body</span> = <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(ctx.<span class="property">body</span>)</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                res.<span class="title function_">end</span>(<span class="string">&#x27;Not Found&#x27;</span>)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;).<span class="title function_">catch</span>(<span class="function"><span class="params">e</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="comment">// 所有的错误都可以在catch中被捕获</span></span><br><span class="line">            <span class="variable language_">this</span>.<span class="title function_">emit</span>(<span class="string">&#x27;error&#x27;</span>, e)</span><br><span class="line">        &#125;)</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">listen</span>(<span class="params">...args</span>) &#123;</span><br><span class="line">        <span class="keyword">const</span> server = http.<span class="title function_">createServer</span>(<span class="variable language_">this</span>.<span class="property">handleRequest</span>);</span><br><span class="line">        server.<span class="title function_">listen</span>(...args)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// callback -&gt; promise</span></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = <span class="title class_">Application</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// koa/lib/context.js</span></span><br><span class="line"><span class="keyword">const</span> context = &#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">defineGetter</span>(<span class="params">property, key</span>) &#123;</span><br><span class="line">    context.<span class="title function_">__defineGetter__</span>(key, <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="variable language_">this</span>[property][key];</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">defineSetter</span>(<span class="params">property, key</span>) &#123;</span><br><span class="line">    context.<span class="title function_">__defineSetter__</span>(key, <span class="keyword">function</span> (<span class="params">value</span>) &#123;</span><br><span class="line">        <span class="variable language_">this</span>[property][key] = value;</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="title function_">defineGetter</span>(<span class="string">&#x27;request&#x27;</span>, <span class="string">&#x27;url&#x27;</span>)</span><br><span class="line"><span class="title function_">defineGetter</span>(<span class="string">&#x27;request&#x27;</span>, <span class="string">&#x27;query&#x27;</span>)</span><br><span class="line"><span class="title function_">defineGetter</span>(<span class="string">&#x27;response&#x27;</span>, <span class="string">&#x27;body&#x27;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="title function_">defineSetter</span>(<span class="string">&#x27;response&#x27;</span>, <span class="string">&#x27;body&#x27;</span>)</span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = context</span><br><span class="line"></span><br><span class="line"><span class="comment">// koa/lib/request.js</span></span><br><span class="line"><span class="keyword">const</span> request = &#123;</span><br><span class="line">    <span class="keyword">get</span> <span class="title function_">url</span>() &#123;</span><br><span class="line">        <span class="comment">// defineProperty</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="property">req</span>.<span class="property">url</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="keyword">get</span> <span class="title function_">path</span>() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">require</span>(<span class="string">&#x27;url&#x27;</span>).<span class="title function_">parse</span>(<span class="variable language_">this</span>.<span class="property">req</span>.<span class="property">url</span>).<span class="property">pathname</span>;</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="keyword">get</span> <span class="title function_">query</span>() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">require</span>(<span class="string">&#x27;url&#x27;</span>).<span class="title function_">parse</span>(<span class="variable language_">this</span>.<span class="property">req</span>.<span class="property">url</span>, <span class="literal">true</span>).<span class="property">query</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = request</span><br><span class="line"></span><br><span class="line"><span class="comment">// koa/lib/response.js</span></span><br><span class="line"><span class="keyword">const</span> response = &#123;</span><br><span class="line">    <span class="attr">_body</span>: <span class="literal">undefined</span>,</span><br><span class="line">    <span class="keyword">get</span> <span class="title function_">body</span>() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="property">_body</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="keyword">set</span> <span class="title function_">body</span>(<span class="params">value</span>) &#123;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">res</span>.<span class="property">statusCode</span> = <span class="number">200</span>;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">_body</span> = value;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = response</span><br><span class="line"></span><br></pre></td></tr></table></figure>
</li>
<li><p>middleware</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// middleware/body-parser.js</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">body</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">async</span> (ctx, next) =&gt; &#123;</span><br><span class="line">        <span class="keyword">await</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">let</span> arr = [];</span><br><span class="line">            ctx.<span class="property">req</span>.<span class="title function_">on</span>(<span class="string">&#x27;data&#x27;</span>, <span class="keyword">function</span> (<span class="params">chunk</span>) &#123;</span><br><span class="line">                arr.<span class="title function_">push</span>(chunk);</span><br><span class="line">            &#125;)</span><br><span class="line">            ctx.<span class="property">req</span>.<span class="title function_">on</span>(<span class="string">&#x27;end&#x27;</span>, <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">                ctx.<span class="property">request</span>.<span class="property">body</span> = <span class="title class_">Buffer</span>.<span class="title function_">concat</span>(arr).<span class="title function_">toString</span>();</span><br><span class="line">                <span class="title function_">resolve</span>()</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;)</span><br><span class="line">        <span class="keyword">return</span> <span class="title function_">next</span>()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = body</span><br></pre></td></tr></table></figure>
</li>
<li><p>1.server.js</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title class_">Koa</span> = <span class="built_in">require</span>(<span class="string">&#x27;./koa&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="keyword">new</span> <span class="title class_">Koa</span>(); <span class="comment">// const app = express()</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 洋葱模型</span></span><br><span class="line"></span><br><span class="line">app.<span class="title function_">use</span>(<span class="keyword">async</span> (ctx) =&gt; &#123; <span class="comment">// req 和 res 在koa中对req和res也进行了封装   request和response （koa自己实现的）  -》 ctx上面</span></span><br><span class="line">    <span class="comment">// req.url  req.method  默认http上面的</span></span><br><span class="line">    <span class="comment">// res.setHeader</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// console.log(ctx.req.url);</span></span><br><span class="line">    <span class="comment">// console.log(ctx.request.req.url);</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// ------</span></span><br><span class="line">    <span class="comment">// console.log(ctx.request.query); // ctx.url == ctx.request.url</span></span><br><span class="line">    <span class="comment">// console.log(ctx.query);</span></span><br><span class="line"></span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(ctx.<span class="property">body</span>)</span><br><span class="line"></span><br><span class="line">    ctx.<span class="property">response</span>.<span class="property">body</span> = <span class="string">&#x27;hello&#x27;</span>;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(ctx.<span class="property">body</span>)</span><br><span class="line">    ctx.<span class="property">response</span>.<span class="property">body</span> = <span class="string">&#x27;world&#x27;</span>;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(ctx.<span class="property">body</span>);</span><br><span class="line"></span><br><span class="line">    ctx.<span class="property">body</span> = <span class="string">&#x27;100&#x27;</span>;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(ctx.<span class="property">response</span>.<span class="property">body</span>)</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.<span class="title function_">listen</span>(<span class="number">3000</span>);</span><br><span class="line"><span class="comment">// koa 50%的功能</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>2.server.js</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title class_">Koa</span> = <span class="built_in">require</span>(<span class="string">&#x27;./koa&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="keyword">new</span> <span class="title class_">Koa</span>(); <span class="comment">// const app = express()</span></span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>);</span><br><span class="line"><span class="comment">// 在使用koa的时候 需要将所有异步的逻辑全部变成 promise 规定 </span></span><br><span class="line"><span class="comment">//  koa要求next前面 必须要加 await 或者return 否则当前执行的逻辑不会等待后面执行完毕</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 洋葱模型</span></span><br><span class="line">app.<span class="title function_">use</span>(<span class="keyword">function</span> (<span class="params">ctx, next</span>) &#123; <span class="comment">// 这个方法在内部会包装成promise</span></span><br><span class="line">    <span class="comment">// res.sendFile()</span></span><br><span class="line">    <span class="comment">// ctx.type = &#x27;&#x27;</span></span><br><span class="line">    <span class="comment">// ctx.set(&#x27;Content-Type&#x27;)</span></span><br><span class="line">    ctx.<span class="property">res</span>.<span class="title function_">setHeader</span>(<span class="string">&#x27;Content-Type&#x27;</span>, <span class="string">&#x27;text/markdown;charset=utf-8&#x27;</span>)</span><br><span class="line">    ctx.<span class="property">body</span> = fs.<span class="title function_">createReadStream</span>(path.<span class="title function_">resolve</span>(__dirname, <span class="string">&#x27;note.md&#x27;</span>))</span><br><span class="line">&#125;)</span><br><span class="line">app.<span class="title function_">use</span>(<span class="keyword">async</span> <span class="keyword">function</span> (<span class="params">ctx, next</span>) &#123; <span class="comment">// 这个方法在内部会包装成promise</span></span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="number">3</span>);</span><br><span class="line">    <span class="keyword">await</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="title function_">resolve</span>()</span><br><span class="line">        &#125;, <span class="number">3000</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="keyword">await</span> <span class="title function_">next</span>();</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="number">4</span>)</span><br><span class="line">&#125;)</span><br><span class="line">app.<span class="title function_">use</span>(<span class="keyword">function</span> (<span class="params">ctx, next</span>) &#123; <span class="comment">// 这个方法在内部会包装成promise</span></span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="number">5</span>);</span><br><span class="line">    <span class="title function_">next</span>();</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="number">6</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">app.<span class="title function_">on</span>(<span class="string">&#x27;error&#x27;</span>, <span class="keyword">function</span> (<span class="params">e</span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;error&#x27;</span>, e)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 因为express 处理错误靠的是错误处理中间件  promise里面可以自己catch。 设计也是为了错误的统一处理</span></span><br><span class="line">app.<span class="title function_">listen</span>(<span class="number">3000</span>);</span><br><span class="line"></span><br></pre></td></tr></table></figure>
</li>
<li><p>3.server.js</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title class_">Koa</span> = <span class="built_in">require</span>(<span class="string">&#x27;koa&#x27;</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> app = <span class="keyword">new</span> <span class="title class_">Koa</span>();</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>).<span class="property">promises</span>;</span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> mime = <span class="built_in">require</span>(<span class="string">&#x27;mime&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> body = <span class="built_in">require</span>(<span class="string">&#x27;./middleware/body-parser&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// koa-router  koa-static koa-session ...</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">static</span>(<span class="params">filepath</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">async</span> <span class="keyword">function</span> (<span class="params">ctx, next</span>) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//  mime.types[path.extname(path.join(filepath, ctx.path))]</span></span><br><span class="line">            <span class="comment">// ctx.type = &#x27;text/html;charset=utf-8&#x27;</span></span><br><span class="line">            ctx.<span class="property">res</span>.<span class="title function_">setHeader</span>(<span class="string">&#x27;Content-Type&#x27;</span>, <span class="string">&#x27;xasdasfref&#x27;</span>)</span><br><span class="line">            ctx.<span class="property">res</span>.<span class="title function_">end</span>(<span class="string">&#x27;ok&#x27;</span>)</span><br><span class="line">        &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(e)</span><br><span class="line">            <span class="keyword">return</span> <span class="title function_">next</span>();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">app.<span class="title function_">use</span>(<span class="title function_">body</span>())</span><br><span class="line">app.<span class="title function_">use</span>(<span class="title function_">static</span>(__dirname))</span><br><span class="line"><span class="comment">// app.use(async function (ctx, next) &#123;</span></span><br><span class="line"><span class="comment">//     // 用户访问 /login 显示一个登录页面</span></span><br><span class="line"><span class="comment">//     if (ctx.path == &#x27;/login&#x27; &amp;&amp; ctx.method === &#x27;GET&#x27;) &#123;</span></span><br><span class="line"><span class="comment">//         ctx.type = &#x27;text/html;charset=utf-8&#x27;</span></span><br><span class="line"><span class="comment">//         ctx.body = fs.createReadStream(path.resolve(__dirname, &#x27;index.html&#x27;));</span></span><br><span class="line"><span class="comment">//     &#125; else &#123;</span></span><br><span class="line"><span class="comment">//         return next();</span></span><br><span class="line"><span class="comment">//     &#125;</span></span><br><span class="line"><span class="comment">// &#125;)</span></span><br><span class="line">app.<span class="title function_">use</span>(<span class="keyword">async</span> <span class="keyword">function</span> (<span class="params">ctx, next</span>) &#123;</span><br><span class="line">    <span class="comment">// 用户点击登录 将用户填写的信息显示到页面上</span></span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(ctx.<span class="property">path</span>, ctx.<span class="property">method</span>)</span><br><span class="line">    <span class="keyword">if</span> (ctx.<span class="property">path</span> === <span class="string">&#x27;/login&#x27;</span> &amp;&amp; ctx.<span class="property">method</span> === <span class="string">&#x27;POST&#x27;</span>) &#123;</span><br><span class="line">        ctx.<span class="property">body</span> = ctx.<span class="property">request</span>.<span class="property">body</span></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        ctx.<span class="property">body</span> = <span class="string">&#x27;not found&#x27;</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">app.<span class="title function_">listen</span>(<span class="number">3000</span>)</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure></li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;IE=edge&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">form</span> <span class="attr">action</span>=<span class="string">&quot;/login&quot;</span> <span class="attr">method</span>=<span class="string">&quot;POST&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">name</span>=<span class="string">&quot;username&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">name</span>=<span class="string">&quot;password&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">button</span>&gt;</span>提交<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/wieldy/bailment-blog/2022/03/29/koa/" data-id="cljmgj1ex000jzc9j5bot8g88" data-title="koa" class="article-share-link">Share</a>
      
      
      
    </footer>
  </div>
  
</article>



  
    <article id="post-mongo" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/bailment-blog/2022/03/29/mongo/" class="article-date">
  <time class="dt-published" datetime="2022-03-29T14:12:00.000Z" itemprop="datePublished">2022-03-29</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="p-name article-title" href="/bailment-blog/2022/03/29/mongo/">mongo</a>
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <ul>
<li>1.server.js<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> mongoose = <span class="built_in">require</span>(<span class="string">&#x27;mongoose&#x27;</span>);</span><br><span class="line"></span><br><span class="line">mongoose.<span class="title function_">connect</span>(<span class="string">`mongodb://127.0.0.1:27017/my`</span>,<span class="keyword">function</span>(<span class="params">err</span>)&#123;</span><br><span class="line">    <span class="keyword">if</span>(err)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="variable language_">console</span>.<span class="title function_">log</span>(err);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;数据库链接成功&#x27;</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title class_">UserModel</span> = <span class="built_in">require</span>(<span class="string">&#x27;./model/user&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> <span class="title class_">ArticleModel</span> = <span class="built_in">require</span>(<span class="string">&#x27;./model/user&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> users = []</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++)&#123;</span><br><span class="line">    users.<span class="title function_">push</span>(&#123;<span class="attr">username</span>:<span class="string">&#x27;zf&#x27;</span>+i,<span class="attr">password</span>:<span class="string">&quot;123456&quot;</span>,<span class="attr">age</span>:i&#125;);</span><br><span class="line">&#125;</span><br><span class="line">(<span class="keyword">async</span> <span class="keyword">function</span>(<span class="params"></span>)&#123;</span><br><span class="line">    <span class="comment">// let docs =  await UserModel.create(users); </span></span><br><span class="line">    <span class="comment">// console.log(docs)</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// find 返回的是数组  findOne / findById</span></span><br><span class="line">    <span class="comment">// let user = await UserModel.findById(&#x27;6290d711a7b5fb00c518030b&#x27;)</span></span><br><span class="line">    <span class="comment">// console.log(user)</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 分页查询 $gt $lt</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// let docs = await UserModel.find(&#123;age:&#123;$gt:3&#125;&#125;); // 原生的方法都支持</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 内部 skip = 3  limit=2   </span></span><br><span class="line">    <span class="comment">// 内置sort 》 skip 》 limit</span></span><br><span class="line">    <span class="comment">// let docs = await UserModel.find(&#123;&#125;).sort(&#123;age:-1&#125;).limit(2).skip(3)</span></span><br><span class="line">    <span class="comment">// console.log(docs)</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// let users = await UserModel.find(&#123;&#125;);</span></span><br><span class="line">    <span class="comment">// console.log(users)</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 关联查询  user  -&gt;  article</span></span><br><span class="line">&#125;)()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="built_in">setTimeout</span>(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">    mongoose.<span class="title function_">disconnect</span>(); <span class="comment">// 关闭链接</span></span><br><span class="line">&#125;,<span class="number">1000</span>)</span><br><span class="line"><span class="comment">// 1) 先链接数据库</span></span><br><span class="line"><span class="comment">// 2) 创建一个模型 （集合、文件集合）</span></span><br><span class="line"><span class="comment">// 3) 文档</span></span><br></pre></td></tr></table></figure></li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> mongoose = <span class="built_in">require</span>(<span class="string">&#x27;mongoose&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> <span class="title class_">UserModel</span> = <span class="built_in">require</span>(<span class="string">&#x27;./model/user&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> <span class="title class_">ArticleModel</span> = <span class="built_in">require</span>(<span class="string">&#x27;./model/article&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> <span class="title class_">CateModel</span> = <span class="built_in">require</span>(<span class="string">&#x27;./model/cate&#x27;</span>);</span><br><span class="line">mongoose.<span class="title function_">connect</span>(<span class="string">`mongodb://127.0.0.1:27017/my`</span>,<span class="keyword">function</span>(<span class="params">err</span>)&#123;</span><br><span class="line">    <span class="keyword">if</span>(err)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="variable language_">console</span>.<span class="title function_">log</span>(err);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;数据库链接成功&#x27;</span>)</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">(<span class="keyword">async</span> <span class="keyword">function</span>(<span class="params"></span>)&#123;</span><br><span class="line">    <span class="comment">// let user =await UserModel.create(&#123;username:&#x27;jw&#x27;,password:&#x27;1234567&#x27;,age:10&#125;);</span></span><br><span class="line">    <span class="comment">// let article =  await ArticleModel.create(&#123;title:&#x27;abc&#x27;,content:&#x27;abc&#x27;,user_id:user._id&#125;);</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 6290dbe8d901a81383d62246</span></span><br><span class="line">    <span class="comment">// let article =  await ArticleModel.findById(&#x27;6290dbe8d901a81383d62246&#x27;)</span></span><br><span class="line">    <span class="comment">// let user = await UserModel.findById(article.user_id)</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// let article =  await ArticleModel.findById(&#x27;6290dbe8d901a81383d62246&#x27;).populate(&#x27;user_id&#x27;,&#123;username:1&#125;);</span></span><br><span class="line">    <span class="comment">// console.log(article)</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 只要复杂的查询全部可以采用聚合查询来解决 aggregate 求平均数 综合， 分组</span></span><br><span class="line">    <span class="comment">// let cate =  await CateModel.create(&#123;title:&#x27;mongo&#x27;&#125;)</span></span><br><span class="line">    <span class="comment">// let article = await ArticleModel.findOneAndUpdate(&#123;_id:&#x27;6290dbe8d901a81383d62246&#x27;&#125;,&#123;cate_id:cate._id&#125;)</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// console.log(article)</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// let article = await ArticleModel.aggregate([ // 这里的方法属性是原生mongodb</span></span><br><span class="line">    <span class="comment">//     &#123;</span></span><br><span class="line">    <span class="comment">//         $lookup:&#123;</span></span><br><span class="line">    <span class="comment">//             from:&#x27;users&#x27;,</span></span><br><span class="line">    <span class="comment">//             localField:&#x27;user_id&#x27;,</span></span><br><span class="line">    <span class="comment">//             foreignField:&#x27;_id&#x27;, // 我的文章中的user_id 关联的是_id</span></span><br><span class="line">    <span class="comment">//             as:&#x27;user&#x27;</span></span><br><span class="line">    <span class="comment">//         &#125;</span></span><br><span class="line">    <span class="comment">//     &#125;,</span></span><br><span class="line">    <span class="comment">//     &#123;</span></span><br><span class="line">    <span class="comment">//         $lookup:&#123;</span></span><br><span class="line">    <span class="comment">//             from:&#x27;cates&#x27;,</span></span><br><span class="line">    <span class="comment">//             localField:&#x27;cate_id&#x27;,</span></span><br><span class="line">    <span class="comment">//             foreignField:&#x27;_id&#x27;, </span></span><br><span class="line">    <span class="comment">//             as:&#x27;cate&#x27;</span></span><br><span class="line">    <span class="comment">//         &#125;</span></span><br><span class="line">    <span class="comment">//     &#125;,</span></span><br><span class="line">    <span class="comment">//     &#123;</span></span><br><span class="line">    <span class="comment">//         $group:&#123;</span></span><br><span class="line">    <span class="comment">//             _id:&#x27;$username&#x27;,</span></span><br><span class="line">                </span><br><span class="line">    <span class="comment">//         &#125;</span></span><br><span class="line">    <span class="comment">//     &#125;,</span></span><br><span class="line">    <span class="comment">//     &#123;</span></span><br><span class="line">    <span class="comment">//         $match:&#123;</span></span><br><span class="line">    <span class="comment">//             _id: mongoose.Types.ObjectId(&#x27;6290dbe8d901a81383d62246&#x27;)</span></span><br><span class="line">    <span class="comment">//         &#125;</span></span><br><span class="line">    <span class="comment">//     &#125;,</span></span><br><span class="line">    <span class="comment">//     &#123;</span></span><br><span class="line">    <span class="comment">//         $project:&#123;</span></span><br><span class="line">    <span class="comment">//             user:&#123;</span></span><br><span class="line">    <span class="comment">//                 username:1</span></span><br><span class="line">    <span class="comment">//             &#125;,</span></span><br><span class="line">    <span class="comment">//             cate:&#123;</span></span><br><span class="line">    <span class="comment">//                 title:1</span></span><br><span class="line">    <span class="comment">//             &#125;</span></span><br><span class="line">    <span class="comment">//         &#125;</span></span><br><span class="line">    <span class="comment">//     &#125;</span></span><br><span class="line">    <span class="comment">// ]);</span></span><br><span class="line">    <span class="comment">// await UserModel.create([&#123;username:&#x27;jw&#x27;,age:20&#125;,&#123;username:&#x27;xxx&#x27;,age:30&#125;])</span></span><br><span class="line">    <span class="keyword">let</span> user = <span class="keyword">await</span> <span class="title class_">UserModel</span>.<span class="title function_">aggregate</span>([ <span class="comment">// 这里的方法属性是原生mongodb</span></span><br><span class="line">        &#123;</span><br><span class="line">            <span class="attr">$group</span>:&#123;</span><br><span class="line">                <span class="attr">_id</span>:<span class="string">&#x27;$username&#x27;</span>, <span class="comment">// 根据哪个字段分组</span></span><br><span class="line">                <span class="attr">age</span>:&#123;<span class="attr">$avg</span>:<span class="string">&#x27;$age&#x27;</span>&#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;,</span><br><span class="line">    ]);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(user)</span><br><span class="line">    </span><br><span class="line">&#125;)()</span><br><span class="line"></span><br><span class="line"><span class="built_in">setTimeout</span>(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">    mongoose.<span class="title function_">disconnect</span>(); <span class="comment">// 关闭链接</span></span><br><span class="line">&#125;,<span class="number">1000</span>)</span><br></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// model/article</span></span><br><span class="line"><span class="keyword">const</span> mongoose = <span class="built_in">require</span>(<span class="string">&#x27;mongoose&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title class_">ArticleSchema</span> = mongoose.<span class="title class_">Schema</span>(&#123;</span><br><span class="line">    <span class="attr">title</span>:<span class="title class_">String</span>,</span><br><span class="line">    <span class="attr">content</span>:<span class="title class_">String</span>,</span><br><span class="line">    <span class="attr">birthday</span>:&#123;</span><br><span class="line">        <span class="attr">type</span>:<span class="title class_">Date</span>,</span><br><span class="line">        <span class="attr">default</span>:<span class="title class_">Date</span>.<span class="property">now</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">user_id</span>:&#123;</span><br><span class="line">        <span class="attr">type</span>:mongoose.<span class="property">SchemaTypes</span>.<span class="property">ObjectId</span>,</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">cate_id</span>:&#123;</span><br><span class="line">        <span class="attr">type</span>:mongoose.<span class="property">SchemaTypes</span>.<span class="property">ObjectId</span>,</span><br><span class="line">    &#125;,  </span><br><span class="line">    <span class="attr">config</span>:&#123;</span><br><span class="line">        <span class="attr">a</span>:&#123;</span><br><span class="line">            <span class="attr">type</span>:<span class="title class_">String</span>,</span><br><span class="line">            <span class="attr">default</span>:<span class="string">&#x27;a&#x27;</span>,</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="attr">b</span>:&#123;</span><br><span class="line">            <span class="attr">type</span>:<span class="title class_">String</span>,</span><br><span class="line">            <span class="attr">default</span>:<span class="string">&#x27;b&#x27;</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = mongoose.<span class="title function_">model</span>(<span class="string">&#x27;Article&#x27;</span>,<span class="title class_">ArticleSchema</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// model/cate.js</span></span><br><span class="line"><span class="keyword">const</span> mongoose = <span class="built_in">require</span>(<span class="string">&#x27;mongoose&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 如果你创建数据的时候 多的是添加不进去的 少的如果不是必填的可以</span></span><br><span class="line"><span class="keyword">const</span> <span class="title class_">CateSchema</span> = mongoose.<span class="title class_">Schema</span>(&#123; <span class="comment">// 1) 骨架</span></span><br><span class="line">    <span class="attr">title</span>:<span class="title class_">String</span></span><br><span class="line">&#125;,&#123;<span class="attr">timestamps</span>:&#123;</span><br><span class="line">    <span class="attr">createAt</span>:<span class="string">&#x27;create&#x27;</span>, <span class="comment">// 改名字, 默认创建时间和 修改时间</span></span><br><span class="line">    <span class="attr">updateAt</span>:<span class="string">&#x27;update&#x27;</span></span><br><span class="line">&#125;&#125;);</span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = mongoose.<span class="title function_">model</span>(<span class="string">&#x27;Cate&#x27;</span>,<span class="title class_">CateSchema</span>); <span class="comment">//UserModel 就可以来操作数据库</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// model/user.js</span></span><br><span class="line"><span class="keyword">const</span> mongoose = <span class="built_in">require</span>(<span class="string">&#x27;mongoose&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 如果你创建数据的时候 多的是添加不进去的 少的如果不是必填的可以</span></span><br><span class="line"><span class="keyword">const</span> <span class="title class_">UserSchema</span> = mongoose.<span class="title class_">Schema</span>(&#123; <span class="comment">// 1) 骨架</span></span><br><span class="line">    <span class="attr">username</span>:&#123;</span><br><span class="line">        <span class="attr">type</span>: <span class="title class_">String</span>,</span><br><span class="line">        <span class="comment">// unique:true,</span></span><br><span class="line">        <span class="attr">trim</span>:<span class="literal">true</span>,</span><br><span class="line">        <span class="attr">lowercase</span>:<span class="literal">true</span>,</span><br><span class="line">        <span class="comment">// required:true</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">password</span>:&#123;</span><br><span class="line">        <span class="attr">type</span>:<span class="title class_">String</span>,</span><br><span class="line">        <span class="attr">validate</span>:&#123;</span><br><span class="line">            <span class="title function_">validator</span>(<span class="params">value</span>)&#123; <span class="keyword">return</span> <span class="literal">true</span>&#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">age</span>:&#123;</span><br><span class="line">        <span class="attr">type</span>:<span class="title class_">Number</span>,</span><br><span class="line">        <span class="attr">default</span>:<span class="number">0</span>,</span><br><span class="line">        <span class="attr">min</span>:<span class="number">0</span>,</span><br><span class="line">        <span class="attr">max</span>:<span class="number">100</span></span><br><span class="line">    &#125;,</span><br><span class="line">&#125;,&#123;<span class="attr">timestamps</span>:&#123;</span><br><span class="line">    <span class="attr">createAt</span>:<span class="string">&#x27;create&#x27;</span>, <span class="comment">// 改名字, 默认创建时间和 修改时间</span></span><br><span class="line">    <span class="attr">updateAt</span>:<span class="string">&#x27;update&#x27;</span></span><br><span class="line">&#125;&#125;);</span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = mongoose.<span class="title function_">model</span>(<span class="string">&#x27;User&#x27;</span>,<span class="title class_">UserSchema</span>); <span class="comment">//UserModel 就可以来操作数据库</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/wieldy/bailment-blog/2022/03/29/mongo/" data-id="cljmgj1ey000kzc9j9ngcdd13" data-title="mongo" class="article-share-link">Share</a>
      
      
      
    </footer>
  </div>
  
</article>



  
    <article id="post-mongo概念" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/bailment-blog/2022/03/29/mongo%E6%A6%82%E5%BF%B5/" class="article-date">
  <time class="dt-published" datetime="2022-03-29T14:12:00.000Z" itemprop="datePublished">2022-03-29</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="p-name article-title" href="/bailment-blog/2022/03/29/mongo%E6%A6%82%E5%BF%B5/">mongo概念</a>
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <ul>
<li>一</li>
</ul>
<h2 id="安装mongo"><a href="#安装mongo" class="headerlink" title="安装mongo"></a>安装mongo</h2><p><a target="_blank" rel="noopener" href="https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-os-x/">https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-os-x/</a></p>
<p>brew services restart mongodb-community</p>
<p>mongod  -》 http.server</p>
<blockquote>
<p>将服务端启动起来了，用客户端来链接服务端</p>
</blockquote>
<h2 id="mongo的概念"><a href="#mongo的概念" class="headerlink" title="mongo的概念"></a>mongo的概念</h2><ul>
<li>数据库  show dbs显示所有的数据库，  use school</li>
<li>文档集合    db.createCollection(‘teachers’)</li>
<li>BSON 默认可以理解成就是一个个的json   <ul>
<li>db.teachers.insert()</li>
<li>db.teachers.find()</li>
<li>db.teachers.update()</li>
<li>db.teachers.remove()</li>
</ul>
</li>
</ul>
<h2 id="可视化工具"><a href="#可视化工具" class="headerlink" title="可视化工具"></a>可视化工具</h2><ul>
<li>Robo 3t  -&gt; studio 3t</li>
<li>navicat</li>
</ul>
<h2 id="curd"><a href="#curd" class="headerlink" title="curd"></a>curd</h2><ul>
<li>db.teachers.insert(插入的数据)</li>
<li>db.teachers.find(绝对的匹配，模糊的匹配, 显示什么)   {a:1,b,c:0} <ul>
<li>模式匹配符号  $or $ne $eq $lt $gt $lte $gte 正则</li>
</ul>
</li>
<li>db.teachers.update(查询条件,修改成什么样子)</li>
<li>db.teachers.remove()</li>
</ul>
<p>存嵌套的文档 而且没有关系的</p>
<h2 id="数据库的导出和备份"><a href="#数据库的导出和备份" class="headerlink" title="数据库的导出和备份"></a>数据库的导出和备份</h2><ul>
<li>mongoexport 导出的是什么格式的 json，csv格式</li>
<li>mongodump</li>
</ul>
<ul>
<li>二</li>
</ul>
<h2 id="什么是MongoDB"><a href="#什么是MongoDB" class="headerlink" title="什么是MongoDB"></a>什么是MongoDB</h2><blockquote>
<p>MongoDB是由C++编写的，基于分布式文件存储的NoSQL数据库。MongoDB中功能丰富是一个介于关系数据库和非关系数据库之间的产品。</p>
</blockquote>
<h2 id="MongoDB适用场景"><a href="#MongoDB适用场景" class="headerlink" title="MongoDB适用场景"></a>MongoDB适用场景</h2><ul>
<li>处理大量低价值的数据而且对处理性能有很高的要求</li>
<li>可以用mongoDB来实现数据的缓存 （缓存层）</li>
<li><h6 id="MongoDB搭建集群环境，实现存储数据横向扩展。"><a href="#MongoDB搭建集群环境，实现存储数据横向扩展。" class="headerlink" title="MongoDB搭建集群环境，实现存储数据横向扩展。"></a>MongoDB搭建集群环境，实现存储数据横向扩展。</h6></li>
</ul>
<h2 id="安装mongoDB"><a href="#安装mongoDB" class="headerlink" title="安装mongoDB"></a>安装mongoDB</h2><p><a target="_blank" rel="noopener" href="https://www.mongodb.com/">MongoDB官方网站</a></p>
<ul>
<li><p>在mac中安装<code>MongoDB</code></p>
<ul>
<li>Homebrew 的包管理器安装 MongoDB</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">brew tap mongodb/brew</span><br><span class="line">brew install mongodb-community@5.0</span><br><span class="line">brew services start mongodb-community@5.0 <span class="comment"># 后台运行</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>在windows中安装<code>MongoDB</code></p>
<ul>
<li>下载 <a target="_blank" rel="noopener" href="https://www.mongodb.com/try/download/community">msi</a> 安装 (不选择 <code>Install MongoDB Compass</code>)</li>
<li><em>mongo.exe</em> 客户端 、<em>mongod.exe</em> 、服务端 <em>mongos</em> 用于注册服务</li>
</ul>
</li>
</ul>
<blockquote>
<p>默认安装后<code>windows</code>是自启动使用27017端口， 我们在命令中输入 <code>mongod --version</code> 显示出对应安装信息则表示安装成功</p>
</blockquote>
<h2 id="Mongo可视化工具"><a href="#Mongo可视化工具" class="headerlink" title="Mongo可视化工具"></a>Mongo可视化工具</h2><ul>
<li><p>Robo 3T</p>
</li>
<li><p>Navicat</p>
</li>
</ul>
<h2 id="Mongo基本操作"><a href="#Mongo基本操作" class="headerlink" title="Mongo基本操作"></a>Mongo基本操作</h2><h3 id="1-链接数据库"><a href="#1-链接数据库" class="headerlink" title="1.链接数据库"></a>1.链接数据库</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">mongo</span><br><span class="line">mongo --host <span class="string">&quot;mongod://xxx:27017&quot;</span> <span class="comment"># 链接到远程数据库</span></span><br></pre></td></tr></table></figure>

<h3 id="2-操作数据库"><a href="#2-操作数据库" class="headerlink" title="2.操作数据库"></a>2.操作数据库</h3><p>MongoDB是一个文档型数据结构。存储的数据是BSON (其实就是我们所谓的json格式) 比json包含更多的数据类型</p>
<ul>
<li>数据库  Database</li>
<li>集合  Collection （表）</li>
<li>文档  Document（数据）</li>
</ul>
<h4 id="1-操作数据库"><a href="#1-操作数据库" class="headerlink" title="1).操作数据库"></a>1).操作数据库</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">show dbs <span class="comment"># 显示全部数据库</span></span><br><span class="line">db <span class="comment"># 显示当前数据库</span></span><br><span class="line">use &lt;DataBaseName&gt; <span class="comment"># 切换到某个数据库中</span></span><br><span class="line">db.dropDatabase() <span class="comment"># 删除数据库</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>切换到某个数库中，像数据库中添加内容时才会创建对应的数据库。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.<span class="title function_">createUser</span>(&#123;<span class="attr">user</span>:<span class="string">&quot;jw&quot;</span>,<span class="string">&quot;pwd&quot;</span>:<span class="string">&quot;jw&quot;</span>,<span class="attr">roles</span>:[&#123;<span class="attr">role</span>:<span class="string">&quot;dbOwner&quot;</span>,<span class="string">&quot;db&quot;</span>:<span class="string">&quot;web&quot;</span>&#125;]&#125;)</span><br><span class="line">db.<span class="title function_">auth</span>() 登录用户</span><br><span class="line">db.<span class="property">student</span>.<span class="title function_">insert</span>(插入的对象) <span class="comment">// 插入数据</span></span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">mongodump --db web --collection student --out backup</span><br><span class="line">mongorestore backup</span><br><span class="line"></span><br><span class="line">mongoexport -d web -c student --csv -f name,a -o a.<span class="property">csv</span> 到出具体格式</span><br><span class="line">mongoimport -d web -c student --type csv --file a.<span class="property">csv</span></span><br></pre></td></tr></table></figure>



<h4 id="2-操作集合"><a href="#2-操作集合" class="headerlink" title="2).操作集合"></a>2).操作集合</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">show collections # 显示所有集合</span><br><span class="line">db.&lt;collectionName&gt;,drop() # 删除集合</span><br></pre></td></tr></table></figure>

<h4 id="3-文档操作"><a href="#3-文档操作" class="headerlink" title="3).文档操作"></a>3).文档操作</h4><p>在集合中的文档数据结构可以不同的，但是在真正使用时我们还是期望结构是相同的，这样更方便操作存储的数据</p>
<h5 id="1-增加数据"><a href="#1-增加数据" class="headerlink" title="1.增加数据"></a>1.增加数据</h5><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">use school;</span><br><span class="line">db.<span class="property">teachers</span>.<span class="title function_">insert</span>(&#123;<span class="attr">name</span>:<span class="string">&quot;zs&quot;</span>,<span class="attr">age</span>:<span class="number">20</span>&#125;); <span class="comment">// 插入数据,自动增加_id字段</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>这里insert方法调用完毕后会返回插入的行数 ， 可以使用<code>insertOne</code>、<code>insertMany</code>插入成功后会返回插入的<code>id</code></p>
</blockquote>
<h5 id="2-查询数据"><a href="#2-查询数据" class="headerlink" title="2.查询数据"></a>2.查询数据</h5><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">db.<span class="property">teachers</span>.<span class="title function_">find</span>(查询条件,显示的字段); <span class="comment">// 查询所有结果</span></span><br><span class="line">db.<span class="property">teachers</span>.<span class="title function_">find</span>(&#123;&#125; <span class="comment">/*查询所有*/</span>,&#123;<span class="attr">name</span>:<span class="number">1</span>&#125; <span class="comment">/*只显示name*/</span>)</span><br></pre></td></tr></table></figure>

<h5 id="3-查询匹配符"><a href="#3-查询匹配符" class="headerlink" title="3.查询匹配符$"></a>3.查询匹配符$</h5><p><strong>比较运算符</strong>:   <code>$gt</code> 、<code>$lt</code> 、<code>$in</code> 、<code>$ne</code>…</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.<span class="property">teachers</span>.<span class="title function_">find</span>(&#123;<span class="attr">age</span>:&#123;<span class="attr">$gt</span>:<span class="number">20</span>&#125;&#125;) </span><br></pre></td></tr></table></figure>

<p><strong>逻辑运算符</strong>:  <code>$or</code>、<code>$not</code>…</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.<span class="property">teachers</span>.<span class="title function_">find</span>(&#123;<span class="attr">$or</span>:[&#123;<span class="attr">age</span>:&#123;<span class="attr">$lt</span>:<span class="number">20</span>&#125;&#125;,&#123;<span class="attr">age</span>:<span class="number">33</span>&#125;]&#125;) <span class="comment">// 或者的关系</span></span><br></pre></td></tr></table></figure>

<h5 id="4-嵌套文档查询"><a href="#4-嵌套文档查询" class="headerlink" title="4.嵌套文档查询"></a>4.嵌套文档查询</h5><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">db.<span class="property">teachers</span>.<span class="title function_">insert</span>(&#123;<span class="attr">name</span>:<span class="string">&quot;jw&quot;</span>,<span class="attr">age</span>:<span class="number">30</span>,<span class="attr">address</span>:&#123;<span class="attr">num</span>:<span class="number">30</span>,<span class="attr">info</span>:<span class="string">&quot;回龙观&quot;</span>&#125;&#125;)</span><br><span class="line">db.<span class="property">teachers</span>.<span class="title function_">find</span>(&#123;<span class="attr">address</span>:&#123;<span class="attr">info</span>:<span class="string">&quot;回龙观&quot;</span>,<span class="attr">num</span>:<span class="number">30</span>&#125;&#125;)</span><br></pre></td></tr></table></figure>

<blockquote>
<p>插入的顺序和查询的顺序不一致则无法正常查询到数据，所以一般不会这样进行嵌套文档查询</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.<span class="property">teachers</span>.<span class="title function_">find</span>(&#123;<span class="string">&quot;address.num&quot;</span>:<span class="number">30</span>,<span class="string">&quot;address.info&quot;</span>:<span class="string">&quot;回龙观&quot;</span>&#125;)</span><br></pre></td></tr></table></figure>

<blockquote>
<p>切记这样才是正规套路</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.<span class="property">teachers</span>.<span class="title function_">insert</span>(&#123;<span class="attr">name</span>:<span class="string">&quot;zry&quot;</span>,<span class="attr">age</span>:<span class="number">40</span>,<span class="attr">address</span>:&#123;<span class="attr">num</span>:<span class="number">40</span>,<span class="attr">info</span>:<span class="string">&quot;回龙观&quot;</span>&#125;,<span class="attr">hobby</span>:[<span class="string">&#x27;drink&#x27;</span>,<span class="string">&#x27;eat&#x27;</span>]&#125;)</span><br><span class="line">db.<span class="property">teachers</span>.<span class="title function_">find</span>(&#123;<span class="attr">hobby</span>:&#123;<span class="attr">$all</span>:[<span class="string">&#x27;eat&#x27;</span>,<span class="string">&#x27;drink&#x27;</span>]&#125;&#125;); <span class="comment">// 查询数组中包含的项</span></span><br><span class="line">db.<span class="property">teachers</span>.<span class="title function_">find</span>(&#123;<span class="attr">hobby</span>:&#123;<span class="attr">$size</span>:<span class="number">2</span>&#125;&#125;); <span class="comment">// 查询数组中包含的项</span></span><br></pre></td></tr></table></figure>

<h5 id="5-更新文档"><a href="#5-更新文档" class="headerlink" title="5.更新文档"></a>5.更新文档</h5><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.<span class="property">teachers</span>.<span class="title function_">update</span>(&#123;<span class="attr">name</span>:<span class="string">&#x27;zs&#x27;</span>&#125;,&#123;<span class="attr">$set</span>:&#123;<span class="attr">age</span>:<span class="number">0</span>&#125;&#125;)</span><br></pre></td></tr></table></figure>

<blockquote>
<p>更新时需要增添$set属性否则会直接覆盖查到的文档</p>
</blockquote>
<h5 id="6-删除文档"><a href="#6-删除文档" class="headerlink" title="6.删除文档"></a>6.删除文档</h5><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.<span class="property">teachers</span>.<span class="title function_">deleteOne</span>(&#123;<span class="attr">name</span>:<span class="string">&#x27;zs&#x27;</span>&#125;); <span class="comment">// 删除某个文档</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>可以通过deleteMany删除多条匹配到的文档</p>
</blockquote>
<h2 id="Mongoose的使用"><a href="#Mongoose的使用" class="headerlink" title="Mongoose的使用"></a>Mongoose的使用</h2><ul>
<li>orm工具方便，而且可以约束存储的内容 </li>
<li><a target="_blank" rel="noopener" href="https://mongoosejs.com/docs/guide.html">文档地址</a></li>
</ul>
<h3 id="1-链接数据库-1"><a href="#1-链接数据库-1" class="headerlink" title="1.链接数据库"></a>1.链接数据库</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> mongoose = <span class="built_in">require</span>(<span class="string">&#x27;mongoose&#x27;</span>);</span><br><span class="line">mongoose.<span class="title function_">connect</span>(<span class="string">`mongodb://127.0.0.1:27017/school`</span>, &#123;</span><br><span class="line">    <span class="attr">useNewUrlParser</span>: <span class="literal">true</span>,</span><br><span class="line">    <span class="attr">useUnifiedTopology</span>: <span class="literal">true</span></span><br><span class="line">&#125;, <span class="keyword">function</span>(<span class="params">err</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (err) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;数据库链接失败&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;链接数据库成功&#x27;</span>)</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h3 id="2-创建Schema"><a href="#2-创建Schema" class="headerlink" title="2.创建Schema"></a>2.创建Schema</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title class_">UserSchema</span> = mongoose.<span class="title class_">Schema</span>(&#123;</span><br><span class="line">    <span class="attr">username</span>:&#123;  <span class="comment">// vue-&gt; props校验</span></span><br><span class="line">        <span class="attr">type</span>:<span class="title class_">String</span>,</span><br><span class="line">        <span class="attr">trim</span>:<span class="literal">true</span>, <span class="comment">// 表示去掉前后空格</span></span><br><span class="line">        <span class="attr">lowercase</span>:<span class="literal">true</span>,</span><br><span class="line">        <span class="attr">required</span>:<span class="literal">true</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">password</span>:&#123;</span><br><span class="line">        <span class="attr">type</span>:<span class="title class_">String</span>, <span class="comment">// 当保存密码的时候</span></span><br><span class="line">        <span class="attr">required</span>:<span class="literal">true</span>,</span><br><span class="line">        <span class="attr">validate</span>:&#123;</span><br><span class="line">            <span class="title function_">validator</span>(<span class="params">value</span>)&#123; <span class="keyword">return</span> <span class="literal">true</span> &#125;<span class="comment">// 返回true表示校验通过</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">age</span>:&#123;</span><br><span class="line">        <span class="attr">type</span>:<span class="title class_">Number</span>,</span><br><span class="line">        <span class="attr">default</span>:<span class="number">6</span>,</span><br><span class="line">        <span class="attr">min</span>:<span class="number">0</span>,</span><br><span class="line">        <span class="attr">max</span>:<span class="number">120</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">gender</span>:&#123;</span><br><span class="line">        <span class="attr">type</span>:<span class="title class_">Number</span>,</span><br><span class="line">        <span class="attr">enum</span>:[<span class="number">0</span>,<span class="number">1</span>]</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;,&#123;</span><br><span class="line">    <span class="attr">timestamps</span>:&#123;</span><br><span class="line">        <span class="attr">createAt</span>:<span class="string">&#x27;createAt&#x27;</span>,</span><br><span class="line">        <span class="attr">updateAt</span>:<span class="string">&#x27;updateAt&#x27;</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="3-创建模型"><a href="#3-创建模型" class="headerlink" title="3.创建模型"></a>3.创建模型</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title class_">UserModel</span> = mongoose.<span class="title function_">model</span>(<span class="string">&#x27;User&#x27;</span>,<span class="title class_">UserSchema</span>,<span class="string">&#x27;user&#x27;</span>);</span><br></pre></td></tr></table></figure>



<h3 id="4-创建数据"><a href="#4-创建数据" class="headerlink" title="4.创建数据"></a>4.创建数据</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [];</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123;</span><br><span class="line">    arr.<span class="title function_">push</span>(&#123; <span class="attr">username</span>: <span class="string">&quot;zs&quot;</span> + i, <span class="attr">password</span>: <span class="string">&quot;abc&quot;</span> + i, <span class="attr">age</span>: i, <span class="attr">gender</span>: <span class="number">0</span> &#125;)</span><br><span class="line">&#125;</span><br><span class="line">;(<span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">    <span class="keyword">let</span> users =  <span class="keyword">await</span> <span class="title class_">UserModel</span>.<span class="title function_">create</span>(arr);</span><br><span class="line">    mongoose.<span class="title function_">disconnect</span>(); <span class="comment">// 断开链接</span></span><br><span class="line">&#125;)();</span><br></pre></td></tr></table></figure>



<h3 id="5-查询数据"><a href="#5-查询数据" class="headerlink" title="5.查询数据"></a>5.查询数据</h3><h4 id="1-基本查询"><a href="#1-基本查询" class="headerlink" title="1.基本查询"></a>1.基本查询</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">(<span class="keyword">async</span> <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> users = <span class="keyword">await</span> <span class="title class_">UserModel</span>.<span class="title function_">find</span>(&#123;</span><br><span class="line">        <span class="attr">$or</span>: [&#123; <span class="attr">username</span>: <span class="string">&#x27;zs1&#x27;</span> &#125;, &#123; <span class="attr">username</span>: <span class="string">&#x27;zs4&#x27;</span> &#125;]</span><br><span class="line">    &#125;, &#123; <span class="attr">age</span>: <span class="number">1</span>, <span class="attr">name</span>: <span class="number">1</span> &#125;);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(users);</span><br><span class="line">    mongoose.<span class="title function_">disconnect</span>(); <span class="comment">// 断开链接</span></span><br><span class="line">&#125;)();</span><br></pre></td></tr></table></figure>

<h4 id="2-分页查询"><a href="#2-分页查询" class="headerlink" title="2.分页查询"></a>2.分页查询</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> limit = <span class="number">3</span>;</span><br><span class="line"><span class="keyword">const</span> currentPage = <span class="number">2</span>;</span><br><span class="line">(<span class="keyword">async</span> <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> users = <span class="keyword">await</span> <span class="title class_">UserModel</span>.<span class="title function_">find</span>(&#123;&#125;).<span class="title function_">skip</span>((currentPage - <span class="number">1</span>) * limit).<span class="title function_">limit</span>(limit).<span class="title function_">sort</span>(&#123; <span class="attr">age</span>: -<span class="number">1</span> &#125;)</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(users);</span><br><span class="line">    mongoose.<span class="title function_">disconnect</span>();</span><br><span class="line">&#125;)()</span><br></pre></td></tr></table></figure>

<h4 id="3-关联查询"><a href="#3-关联查询" class="headerlink" title="3.关联查询"></a>3.关联查询</h4><p>创建文章集合，存储时让用户关联文章数据</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title class_">ArticleSchema</span> = <span class="keyword">new</span> mongoose.<span class="title class_">Schema</span>(&#123;</span><br><span class="line">    <span class="attr">title</span>: <span class="title class_">String</span>,</span><br><span class="line">    <span class="attr">content</span>: <span class="title class_">String</span>,</span><br><span class="line">    <span class="attr">createTime</span>: &#123;</span><br><span class="line">        <span class="attr">type</span>: <span class="title class_">Date</span>,</span><br><span class="line">        <span class="attr">default</span>: <span class="title class_">Date</span>.<span class="property">now</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">user_id</span>:&#123;</span><br><span class="line">        <span class="attr">type</span>:mongoose.<span class="property">SchemaTypes</span>.<span class="property">ObjectId</span>,</span><br><span class="line">        <span class="attr">ref</span>:<span class="string">&#x27;User&#x27;</span></span><br><span class="line">    &#125; <span class="comment">// 用户的_id 类型就是ObjectId</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">const</span> <span class="title class_">ArticleModel</span> = mongoose.<span class="title function_">model</span>(<span class="string">&#x27;Article&#x27;</span>, <span class="title class_">ArticleSchema</span>,<span class="string">&#x27;article&#x27;</span>);</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">(<span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">    <span class="keyword">let</span> user = <span class="keyword">await</span> <span class="title class_">UserModel</span>.<span class="title function_">create</span>(&#123; <span class="attr">username</span>: <span class="string">&#x27;jw&#x27;</span>, <span class="attr">password</span>: <span class="string">&#x27;jw&#x27;</span> &#125;);</span><br><span class="line">    <span class="keyword">let</span> article =<span class="keyword">await</span> <span class="title class_">ArticleModel</span>.<span class="title function_">create</span>(&#123; <span class="attr">title</span>: <span class="string">&#x27;MongoDB&#x27;</span>, <span class="attr">content</span>: <span class="string">&#x27;如何使用&#x27;</span>, <span class="attr">user_id</span>: user.<span class="property">_id</span> &#125;);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(article);</span><br><span class="line">&#125;)();</span><br></pre></td></tr></table></figure>

<h5 id="3-1-populate"><a href="#3-1-populate" class="headerlink" title="3.1 populate"></a>3.1 <code>populate</code></h5><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">(<span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">    <span class="keyword">let</span> r = <span class="keyword">await</span> <span class="title class_">ArticleModel</span>.<span class="title function_">findById</span>(<span class="string">&#x27;61b32f1ab860e70c9836efcc&#x27;</span>).<span class="title function_">populate</span>(<span class="string">&#x27;user_id&#x27;</span>);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(r);</span><br><span class="line">&#125;)();</span><br></pre></td></tr></table></figure>

<h5 id="3-2-aggregate"><a href="#3-2-aggregate" class="headerlink" title="3.2 aggregate"></a>3.2 aggregate</h5><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> r = <span class="keyword">await</span> <span class="title class_">ArticleModel</span>.<span class="title function_">aggregate</span>([</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="attr">$lookup</span>:&#123;</span><br><span class="line">            <span class="attr">from</span>:<span class="string">&#x27;user&#x27;</span>, <span class="comment">// 通过文章 查询用户</span></span><br><span class="line">            <span class="attr">localField</span>:<span class="string">&#x27;user_id&#x27;</span>, <span class="comment">// 通过文章的localField 关联foreginFiled</span></span><br><span class="line">            <span class="attr">foreignField</span>:<span class="string">&quot;_id&quot;</span>,</span><br><span class="line">            <span class="attr">as</span>:<span class="string">&#x27;user&#x27;</span> <span class="comment">// 查到的结果 放到user字段中</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="attr">$match</span>:&#123;</span><br><span class="line">            <span class="attr">_id</span>:mongoose.<span class="property">Types</span>.<span class="title class_">ObjectId</span>(<span class="string">&#x27;61b32f1ab860e70c9836efcc&#x27;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="attr">$project</span>:&#123; <span class="comment">// 和我们写的populate第二个参数功能一样,只显示用户的字段</span></span><br><span class="line">            <span class="attr">user</span>:<span class="number">1</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">/*&#123;  根据字段进行分组</span></span><br><span class="line"><span class="comment">         $group:&#123;</span></span><br><span class="line"><span class="comment">             _id:&#x27;$username&#x27;,</span></span><br><span class="line"><span class="comment">             age:&#123;$sum:&quot;$age&quot;&#125;</span></span><br><span class="line"><span class="comment">         &#125;</span></span><br><span class="line"><span class="comment">     &#125;*/</span></span><br><span class="line">])</span><br></pre></td></tr></table></figure>

<h3 id="6-修改数据"><a href="#6-修改数据" class="headerlink" title="6.修改数据"></a>6.修改数据</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">(<span class="keyword">async</span> <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> doc = <span class="keyword">await</span> <span class="title class_">UserModel</span>.<span class="title function_">updateOne</span>(&#123; <span class="attr">username</span>: <span class="string">&#x27;111&#x27;</span> &#125;, &#123; <span class="attr">username</span>: <span class="string">&#x27;xxx&#x27;</span> &#125;, &#123; <span class="attr">upsert</span>: <span class="literal">true</span> &#125;)</span><br><span class="line">    mongoose.<span class="title function_">disconnect</span>();</span><br><span class="line">&#125;)()</span><br></pre></td></tr></table></figure>

<h3 id="7-删除数据"><a href="#7-删除数据" class="headerlink" title="7.删除数据"></a>7.删除数据</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">(<span class="keyword">async</span> <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> r = <span class="keyword">await</span> <span class="title class_">UserModel</span>.<span class="title function_">deleteOne</span>(&#123;<span class="attr">username</span>:<span class="string">&#x27;xxx&#x27;</span>&#125;)</span><br><span class="line">    mongoose.<span class="title function_">disconnect</span>(r);</span><br><span class="line">&#125;)()</span><br></pre></td></tr></table></figure>

<h2 id="Mongoose扩展"><a href="#Mongoose扩展" class="headerlink" title="Mongoose扩展"></a>Mongoose扩展</h2><h3 id="1-模型扩展"><a href="#1-模型扩展" class="headerlink" title="1.模型扩展"></a>1.模型扩展</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="title class_">UserSchema</span>.<span class="property">statics</span>.<span class="property">findByName</span> = <span class="keyword">function</span> (<span class="params">username</span>) &#123; <span class="comment">// 相当于在模型上直接扩展方法</span></span><br><span class="line">    <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="title function_">findOne</span>(&#123;username&#125;)</span><br><span class="line">&#125;</span><br><span class="line"><span class="title class_">UserModel</span>.<span class="title function_">findByName</span>(<span class="string">&quot;jw&quot;</span>); </span><br></pre></td></tr></table></figure>

<h3 id="2-实例扩展"><a href="#2-实例扩展" class="headerlink" title="2.实例扩展"></a>2.实例扩展</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="title class_">UserSchema</span>.<span class="property">methods</span>.<span class="property">saveMd5</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">password</span> = <span class="built_in">require</span>(<span class="string">&#x27;crypto&#x27;</span>).<span class="title function_">createHash</span>(<span class="string">&#x27;md5&#x27;</span>).<span class="title function_">update</span>(<span class="variable language_">this</span>.<span class="property">password</span>).<span class="title function_">digest</span>(<span class="string">&#x27;base64&#x27;</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="title function_">save</span>();</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">new</span> <span class="title class_">UserModel</span>(&#123;<span class="attr">username</span>:<span class="string">&#x27;zf&#x27;</span>,<span class="attr">password</span>:<span class="string">&#x27;123&#x27;</span>&#125;).<span class="title function_">save</span>();</span><br></pre></td></tr></table></figure>

<h3 id="3-插件扩展"><a href="#3-插件扩展" class="headerlink" title="3.插件扩展"></a>3.插件扩展</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">plugin</span>(<span class="params">schema,options</span>)&#123; <span class="comment">// 将方法进行了封装</span></span><br><span class="line">    schema.<span class="title function_">virtual</span>(<span class="string">&#x27;usernameAndAge&#x27;</span>).<span class="title function_">get</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="property">username</span> + <span class="string">&quot;:&quot;</span> + <span class="variable language_">this</span>.<span class="property">password</span></span><br><span class="line">    &#125;); <span class="comment">// 提取公共逻辑</span></span><br><span class="line">    schema.<span class="title function_">pre</span>(<span class="string">&#x27;save&#x27;</span>,<span class="keyword">function</span> (<span class="params">next</span>) &#123; </span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(options);</span><br><span class="line">        <span class="title function_">next</span>(); <span class="comment">// 之前 格式化数据  之后 一般都是存储日志 后续操作</span></span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"><span class="title class_">UserSchema</span>.<span class="title function_">plugin</span>(plugin,&#123;<span class="attr">a</span>:<span class="number">1</span>&#125;); </span><br></pre></td></tr></table></figure>


      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/wieldy/bailment-blog/2022/03/29/mongo%E6%A6%82%E5%BF%B5/" data-id="cljmgj1ey000lzc9j6rd06208" data-title="mongo概念" class="article-share-link">Share</a>
      
      
      
    </footer>
  </div>
  
</article>



  
    <article id="post-node" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/bailment-blog/2022/03/29/node/" class="article-date">
  <time class="dt-published" datetime="2022-03-29T14:12:00.000Z" itemprop="datePublished">2022-03-29</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="p-name article-title" href="/bailment-blog/2022/03/29/node/">node</a>
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <ul>
<li><p>code</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// let str = require(&#x27;./test.js&#x27;);</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 1) 要读取文件内容</span></span><br><span class="line"><span class="comment">// 2) 包装函数</span></span><br><span class="line"><span class="comment">// 3) 默认返回module.exports</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>); <span class="comment">// 处理路径</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// join / resolve 用的时候可以混用</span></span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(path.<span class="title function_">join</span>(<span class="string">&#x27;a&#x27;</span>, <span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;c&#x27;</span>, <span class="string">&#x27;..&#x27;</span>, <span class="string">&#x27;/&#x27;</span>))</span><br><span class="line"></span><br><span class="line"><span class="comment">// 根据已经有的路径来解析绝对路径， 可以用他来解析配置文件</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(path.<span class="title function_">resolve</span>(<span class="string">&#x27;a&#x27;</span>, <span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;/&#x27;</span>)); <span class="comment">// resolve 不支持/ 会解析成根路径</span></span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(path.<span class="title function_">join</span>(__dirname, <span class="string">&#x27;a&#x27;</span>))</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(path.<span class="title function_">extname</span>(<span class="string">&#x27;1.js&#x27;</span>))</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(path.<span class="title function_">dirname</span>(__dirname)); <span class="comment">// 解析父目录</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>); <span class="comment">// file system</span></span><br><span class="line"><span class="comment">// 同步读取</span></span><br><span class="line"><span class="keyword">let</span> content = fs.<span class="title function_">readFileSync</span>(path.<span class="title function_">resolve</span>(__dirname, <span class="string">&#x27;test.js&#x27;</span>), <span class="string">&#x27;utf8&#x27;</span>);</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(content);</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> exists = fs.<span class="title function_">existsSync</span>(path.<span class="title function_">resolve</span>(__dirname, <span class="string">&#x27;test1.js&#x27;</span>));</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(exists);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> vm = <span class="built_in">require</span>(<span class="string">&#x27;vm&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 我的目的是让字符串变成可以执行的代码, 想让字符串执行 不能采用eval， 会有上下文依赖问题，</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">eval</span>(<span class="string">&#x27;console.log()&#x27;</span>);  <span class="comment">// new Function 可以创造一个顶级的函数，也没有上下文的问题。 但是node中没有使用他</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> a = <span class="number">1</span></span><br><span class="line">vm.<span class="title function_">runInThisContext</span>(<span class="string">&quot;a = 100&quot;</span>); <span class="comment">// 沙箱，独立的环境</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(a)</span><br><span class="line"></span><br><span class="line"><span class="comment">// join resolve dirname</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
</li>
<li><p>module</p>
</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> vm = <span class="built_in">require</span>(<span class="string">&#x27;vm&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> &#123; dir &#125; = <span class="built_in">require</span>(<span class="string">&#x27;console&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">Module</span>(<span class="params">id</span>) &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">id</span> = id;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">exports</span> = &#123;&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="title class_">Module</span>.<span class="property">_extensions</span> = &#123;</span><br><span class="line">    <span class="string">&#x27;.js&#x27;</span>(<span class="variable language_">module</span>) &#123;</span><br><span class="line">        <span class="keyword">const</span> content = fs.<span class="title function_">readFileSync</span>(<span class="variable language_">module</span>.<span class="property">id</span>, <span class="string">&#x27;utf8&#x27;</span>);</span><br><span class="line">        <span class="keyword">let</span> wrapperFn = vm.<span class="title function_">compileFunction</span>(content, [</span><br><span class="line">            <span class="string">&#x27;exports&#x27;</span>, <span class="string">&#x27;require&#x27;</span>, <span class="string">&#x27;module&#x27;</span>, <span class="string">&#x27;__filename&#x27;</span>, <span class="string">&#x27;__dirname&#x27;</span></span><br><span class="line">        ]);</span><br><span class="line">        <span class="keyword">let</span> <span class="built_in">exports</span> = <span class="variable language_">this</span>.<span class="property">exports</span>;</span><br><span class="line">        <span class="keyword">let</span> thisValue = <span class="built_in">exports</span></span><br><span class="line">        <span class="keyword">let</span> <span class="built_in">require</span> = req;</span><br><span class="line">        <span class="keyword">let</span> filename = <span class="variable language_">module</span>.<span class="property">id</span></span><br><span class="line">        <span class="keyword">let</span> dirname = path.<span class="title function_">dirname</span>(filename);</span><br><span class="line"></span><br><span class="line">        <span class="title class_">Reflect</span>.<span class="title function_">apply</span>(wrapperFn, thisValue, [<span class="built_in">exports</span>, <span class="built_in">require</span>, <span class="variable language_">module</span>, filename, dirname])</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="string">&#x27;.json&#x27;</span>() &#123; &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="title class_">Module</span>.<span class="property">_resolveFilename</span> = <span class="keyword">function</span> (<span class="params">id</span>) &#123;</span><br><span class="line">    <span class="keyword">const</span> filepath = path.<span class="title function_">resolve</span>(id);</span><br><span class="line">    <span class="keyword">if</span> (fs.<span class="title function_">existsSync</span>(filepath)) <span class="keyword">return</span> filepath</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> exts = <span class="title class_">Object</span>.<span class="title function_">keys</span>(<span class="title class_">Module</span>.<span class="property">_extensions</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 尝试添加后缀</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; exts.<span class="property">length</span>; i++) &#123;</span><br><span class="line">        <span class="keyword">let</span> file = filepath + exts[i];</span><br><span class="line">        <span class="keyword">if</span> (fs.<span class="title function_">existsSync</span>(file)) <span class="keyword">return</span> file</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">Error</span>(<span class="string">&#x27;Cannot find module:&#x27;</span> + id)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="title class_">Module</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">load</span> = <span class="keyword">function</span> (<span class="params">filename</span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> ext = path.<span class="title function_">extname</span>(filename);</span><br><span class="line">    <span class="title class_">Module</span>.<span class="property">_extensions</span>[ext](<span class="variable language_">this</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">req</span>(<span class="params">id</span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> absPath = <span class="title class_">Module</span>.<span class="title function_">_resolveFilename</span>(id);</span><br><span class="line">    <span class="keyword">const</span> <span class="variable language_">module</span> = <span class="keyword">new</span> <span class="title class_">Module</span>(absPath);</span><br><span class="line">    <span class="variable language_">module</span>.<span class="title function_">load</span>(absPath)</span><br><span class="line">    <span class="keyword">return</span> <span class="variable language_">module</span>.<span class="property">exports</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> str = <span class="title function_">req</span>(<span class="string">&#x27;./test&#x27;</span>)</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(str);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 怎么调试代码vscode</span></span><br><span class="line"><span class="comment">// 添加 launch.json 文件，并且取消忽略源代码</span></span><br><span class="line"><span class="comment">// 知道调试的文件， 在对应的地方打断点</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 看源码 先掌握核心思路 之后在写个mini版本的</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 1) require 一个模块 默认会调用Module._load方法</span></span><br><span class="line"><span class="comment">// 2) Module._resolveFilename 解析文件名 默认会自动添加.js,.json  要文件名的目的就是为了能读取文件</span></span><br><span class="line"><span class="comment">// 3) 创建当前模块的实例 const module =  new Module() =&gt; &#123;id:文件名,exports:&#123;&#125;&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 4） module.load 根据刚才得到的文件名来进行模块的加载</span></span><br><span class="line"><span class="comment">//      5)  根据文件的后缀调用注册的方法（策略模式）</span></span><br><span class="line"><span class="comment">//      6)  加载js文件， 读取文件的内容</span></span><br><span class="line"><span class="comment">//      7)  module._compile 给读取到的内容包装函数  vm.compileFunction()   &#x27;exports&#x27;, &#x27;require&#x27;, &#x27;module&#x27;,&#x27;__filename&#x27;, &#x27;__dirname&#x27;,</span></span><br><span class="line"><span class="comment">// 8) 就是执行这个函数将module传递给用户  （用户会手动的给module.exportsf赋值）</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 9）最终返回的就是 module.exports</span></span><br></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//test.js</span></span><br><span class="line"><span class="keyword">let</span> str = <span class="string">&#x27;hello world&#x27;</span></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = str</span><br></pre></td></tr></table></figure>

<p>消息队列 其实在内部是有多个队列的， 理解的时候 我们说宏任务只有一个<br>一个任务队列（集合）是有多个队列组成的  每个队列中有多个任务<br>选择要执行的队列</p>
<blockquote>
<p>我们直接理解成只有一个宏任务队列（其实是有多个的）</p>
</blockquote>
<p>微任务是一个独立的队列  每次宏任务会产生一个微任务队列</p>
<h2 id="node-概念是什么，-是什么东西-，能做哪些事"><a href="#node-概念是什么，-是什么东西-，能做哪些事" class="headerlink" title="node 概念是什么， 是什么东西 ，能做哪些事"></a>node 概念是什么， 是什么东西 ，能做哪些事</h2><p>node不是语言，是一个运行时 （提供了一个js的运行环境） js的组成部分（ECMAScript、DOM、BOM） 在node中支持 ECMAScript， node中增添了很多内置的模块各种各样的功能 + 第三方模块</p>
<blockquote>
<p>简单理解 js + 内置的模块 + 别人写好的模块</p>
</blockquote>
<h2 id="js特点是主线程是单线程的"><a href="#js特点是主线程是单线程的" class="headerlink" title="js特点是主线程是单线程的"></a>js特点是主线程是单线程的</h2><p>多线程和单线程的区别  java  node</p>
<blockquote>
<p>多线程语言，多个请求到来的时候 需要开启对应的线程来进行处理 （线程池，解决防止开启大量线程，浪费内存） 超过处理个数后需要等待 （好处就是每一个人都能处理复杂的逻辑）  比较适合cpu密集型 （压缩，解密，加密） 后面的请求处理不用等待第一个人的处理  （同时操作同一个资源需要上锁）   同步阻塞</p>
</blockquote>
<blockquote>
<p>单线程的特点就是第一个处理后处理第二个（节约内存，不需要开启线程），  如果第一个人处理完后，会通知线程回来处理  适合io密集型（异步） 稍后完成了在回来处理（事件通知 ） 底层有一个事件环的机制    文件读取写入 （web开发） Nginx （单线程模型）  单线程（没有锁的概念）  异步非阻塞，完成后通知我</p>
</blockquote>
<p>同步&#x2F;异步    阻塞&#x2F;非阻塞</p>
<blockquote>
<p>阻塞非阻塞指代的是调用方的状态   同步异步指代的是被调用的状态</p>
</blockquote>
<p>多线程，单线程，阻塞非阻塞，同步和异步  （webpack多线程打包） </p>
<h2 id="node使用场景？"><a href="#node使用场景？" class="headerlink" title="node使用场景？"></a>node使用场景？</h2><ul>
<li>服务端, 我们目前多数采用中间层 （前后端分离的项目：可以解决跨域问题，可以做数据处理）</li>
<li>工具 gulp webpack vite 微前端工程化而生  node对js支持</li>
<li>ssr 服务端渲染  （vue和react来做处理） -》 node来做</li>
</ul>
<h2 id="模块的问题"><a href="#模块的问题" class="headerlink" title="模块的问题"></a>模块的问题</h2><ul>
<li>为什么要有模块化 （方便维护，高内聚低耦合，变量冲突问题） 前端可以通过单例模式来解决</li>
<li>js实现模块化可以采用函数来进行分割 ， node中也是采用函数来进行模块划分的</li>
<li>cmd(seajs) amd(require) umd(支持amd ，cmd的) iife （自执行函数） commonjs （require module.exports） es6 (import export ) systemjs (微前端 jsonp)….  规范</li>
</ul>
<blockquote>
<p>前端 es6Module   后端 commonjs  (后端也慢慢的开始转向es6模块了)</p>
</blockquote>
<h2 id="commonjs规范"><a href="#commonjs规范" class="headerlink" title="commonjs规范"></a>commonjs规范</h2><ul>
<li>每个js文件都是一个模块</li>
<li>每个模块想去引用别人的模块 需要采用require语法</li>
<li>每个模块想被别人使用需要采用 module.exports 导出</li>
</ul>
<h2 id="内置模块"><a href="#内置模块" class="headerlink" title="内置模块"></a>内置模块</h2><blockquote>
<p>天生的与生俱来的</p>
</blockquote>
<h2 id="文件模块"><a href="#文件模块" class="headerlink" title="文件模块"></a>文件模块</h2>
      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/wieldy/bailment-blog/2022/03/29/node/" data-id="cljmgj1ey000mzc9jd8g7ge1i" data-title="node" class="article-share-link">Share</a>
      
      
      
    </footer>
  </div>
  
</article>



  
    <article id="post-stream" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/bailment-blog/2022/03/29/stream/" class="article-date">
  <time class="dt-published" datetime="2022-03-29T14:12:00.000Z" itemprop="datePublished">2022-03-29</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="p-name article-title" href="/bailment-blog/2022/03/29/stream/">stream</a>
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <ul>
<li><p>buffer</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// buffer 代表的就是缓存区域的内容，早期js没有读取文件的能力 （前端多数都是字符串）。 在node中读取出的内容都是二进制格式</span></span><br><span class="line"><span class="comment">// buffer优点可以将二进制和我们的字符串相互转化  buffer代表的是内存 （内存地址 引用类型） buffer默认声明的时候都是固定大小的</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 声明buffer的三种方式</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> b1 = <span class="title class_">Buffer</span>.<span class="title function_">from</span>(<span class="string">&#x27;珠峰&#x27;</span>); <span class="comment">// node中默认不支持gbk编码 (在utf8中一个汉字是三个字节)</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(b1.<span class="title function_">toString</span>(<span class="string">&#x27;base64&#x27;</span>)); <span class="comment">// 可以将buffer转成对应的编码 utf8/base64</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> b2 = <span class="title class_">Buffer</span>.<span class="title function_">alloc</span>(<span class="number">6</span>); <span class="comment">// buffer中的单位都是字节（最小单位了）</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(b2);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> b3 = <span class="title class_">Buffer</span>.<span class="title function_">from</span>([<span class="number">0x64</span>, <span class="number">100</span>, <span class="string">&#x27;abc&#x27;</span>, <span class="number">257</span>]); <span class="comment">// 这种方式基本用不到</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(b3)</span><br><span class="line"></span><br><span class="line"><span class="comment">// ascii  -&gt;  gb18030  -&gt; gbk -&gt; unicode  -&gt; utf8</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title class_">Buffer</span>.<span class="title function_">from</span>(<span class="string">&#x27;abc&#x27;</span>)); <span class="comment">// 字符串是1个字符1个字节 应用的是ASCII</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 我们要掌握buffer的常用方法和基本的api</span></span><br><span class="line"><span class="comment">// 将多个buffer拼接在一起</span></span><br><span class="line"><span class="keyword">const</span> b4 = <span class="title class_">Buffer</span>.<span class="title function_">from</span>(<span class="string">&#x27;珠峰&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> b5 = <span class="title class_">Buffer</span>.<span class="title function_">from</span>(<span class="string">&#x27;架构&#x27;</span>);  <span class="comment">// 扩容处理 （就是声明一个更大的将以前的放进去） copy</span></span><br><span class="line"><span class="title class_">Buffer</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">copy</span> = <span class="keyword">function</span> (<span class="params">target, targetStart, sourceStart = <span class="number">0</span>, sourceEnd = <span class="variable language_">this</span>.length</span>) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; sourceEnd - sourceStart; i++) &#123;</span><br><span class="line">        target[targetStart + i] = <span class="variable language_">this</span>[sourceStart + i]; <span class="comment">// buffer中存放的都是引用类型</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/* const bigBuffer = Buffer.alloc(b4.length + b5.length); // 取的是字节长度</span></span><br><span class="line"><span class="comment">b4.copy(bigBuffer, 0) // npm install @types/node (node中的ts的声明文件)</span></span><br><span class="line"><span class="comment">b5.copy(bigBuffer, b4.length);</span></span><br><span class="line"><span class="comment">b6.copy(bigBuffer, b4.length + b5.length);</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="title class_">Buffer</span>.<span class="property">concat</span> = <span class="keyword">function</span> (<span class="params">list, totalLength = list.reduce((memo, current) =&gt; memo += current.length, <span class="number">0</span>)</span>) &#123;</span><br><span class="line">    <span class="keyword">const</span> bigBuffer = <span class="title class_">Buffer</span>.<span class="title function_">alloc</span>(totalLength);</span><br><span class="line">    <span class="keyword">let</span> pos = <span class="number">0</span>;</span><br><span class="line">    list.<span class="title function_">forEach</span>(<span class="function"><span class="params">buf</span> =&gt;</span> &#123;</span><br><span class="line">        buf.<span class="title function_">copy</span>(bigBuffer, pos);</span><br><span class="line">        pos += buf.<span class="property">length</span></span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">return</span> bigBuffer</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> bigBuffer = <span class="title class_">Buffer</span>.<span class="title function_">concat</span>([b4, b5]); <span class="comment">// 这个方法经常用到</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 如果自己分析数据 行读取器 每读取一行就打印一下，  遇到关键字就做处理</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> buf = <span class="title class_">Buffer</span>.<span class="title function_">from</span>(<span class="string">&#x27;1---哈哈---name=zf---age=13&#x27;</span>);</span><br><span class="line"><span class="title class_">Buffer</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">split</span> = <span class="keyword">function</span> (<span class="params">sep</span>) &#123;</span><br><span class="line">    sep = <span class="title class_">Buffer</span>.<span class="title function_">isBuffer</span>(sep) ? sep : <span class="title class_">Buffer</span>.<span class="title function_">from</span>(sep);</span><br><span class="line">    <span class="keyword">let</span> len = sep.<span class="property">length</span>; <span class="comment">// 是对应分割符的长度 是以字节为单位的</span></span><br><span class="line">    <span class="keyword">let</span> arr = [];</span><br><span class="line">    <span class="keyword">let</span> offset = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">let</span> idx = <span class="number">0</span>;</span><br><span class="line">    <span class="comment">// this的indexOf （buffer）</span></span><br><span class="line">    <span class="keyword">while</span> (-<span class="number">1</span> !== (idx = <span class="variable language_">this</span>.<span class="title function_">indexOf</span>(sep, offset))) &#123;</span><br><span class="line">        arr.<span class="title function_">push</span>(<span class="variable language_">this</span>.<span class="title function_">slice</span>(offset, idx));</span><br><span class="line">        offset = idx + len</span><br><span class="line">    &#125;</span><br><span class="line">    arr.<span class="title function_">push</span>(<span class="variable language_">this</span>.<span class="title function_">slice</span>(offset))</span><br><span class="line">    <span class="keyword">return</span> arr;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> arr = buf.<span class="title function_">split</span>(<span class="string">&#x27;---&#x27;</span>); <span class="comment">// 字符串的indexof</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(arr)</span><br><span class="line"></span><br><span class="line"><span class="comment">// Buffer.concat()  buffer.slice() 我们事先声明了一个100字节的buffer，但是最终只有10个有效，我们可以截取出来</span></span><br><span class="line"><span class="comment">// Buffer.isBuffer() 可以判断是不是buffer类型  我们可以统一将数据全部处理成buffer来进行操作</span></span><br><span class="line"><span class="comment">// buffer.indexOf() 可以基于封装split方法</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 和数组来类比buffer    slice()截取</span></span><br><span class="line"><span class="comment">// let arr = [[0], 1, 2, 3];</span></span><br><span class="line"><span class="comment">// const newArray = arr.slice(0, 1); // 截取的是内存空间</span></span><br><span class="line"><span class="comment">// newArray[0][0] = 100;</span></span><br><span class="line"><span class="comment">// console.log(arr)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// // ------------------------</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// let b7 = Buffer.from([1, 2, 3, 4, 5, 6]);</span></span><br><span class="line"><span class="comment">// let b8 = b7.slice(0, 1);</span></span><br><span class="line"><span class="comment">// b8[0] = 100;</span></span><br><span class="line"><span class="comment">// console.log(b7)</span></span><br></pre></td></tr></table></figure></li>
<li><p>fs</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 文件读取等操作 都是操作的都是二进制数据  fs filesystem</span></span><br><span class="line"><span class="comment">// fs.readFileSync() 同步性能 （缺陷是阻塞主线程）  fs.readFile()  （异步的非阻塞）</span></span><br><span class="line"><span class="comment">// fs.writeFileSync()                            fs.writeFile()</span></span><br><span class="line"><span class="comment">// 默认我们在做一些前置工作的时候 （前置工作采用同步的）  在程序运行的过程中防止阻塞主线程（需要采用异步）</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 拷贝一个文件</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 写入的特点是： 如果文件不存在会创建这个文件，如果文件存在，默认会清空文件 （最后写入）</span></span><br><span class="line"><span class="comment">// 读取的特点是： 如果文件不存在会报错</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 简单的文件读取是ok的~ 但是如果文件大的话不能采用这种方式。  流 （采用边读边写入的方式，暂停，控制速率的功能）</span></span><br><span class="line"><span class="comment">// fs.readFile(path.join(__dirname, &#x27;package.json&#x27;), function (err, data) &#123; // error -first模式第一个参数是错误</span></span><br><span class="line"><span class="comment">//     if (err) return err;</span></span><br><span class="line"><span class="comment">//     fs.writeFile(path.join(__dirname, &#x27;package1.json&#x27;), data, function (err) &#123;</span></span><br><span class="line"><span class="comment">//         console.log(err, &#x27;写入的err&#x27;)</span></span><br><span class="line"><span class="comment">//     &#125;)</span></span><br><span class="line"><span class="comment">// &#125;);</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// fs.open()  fs.read()  fs.write()  fs.close()  也有同步的但是主要应用还是异步api</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 64k以下的可以采用这种方式</span></span><br><span class="line"><span class="comment">// r读取  w写入  a追加</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 所谓的读取 都是写入 （是把文件中的内容，写入到内存中）</span></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">const BUFFER_SIZE = 3;</span></span><br><span class="line"><span class="comment">const buffer = Buffer.alloc(BUFFER_SIZE);</span></span><br><span class="line"><span class="comment">fs.open(path.resolve(__dirname, &#x27;test&#x27;), &#x27;r&#x27;, function (err, fd) &#123; // file descriptor 文件描述符（描述如何操作这个文件）</span></span><br><span class="line"><span class="comment">    // 将数据写入到buffer中 从第0个索引开始写入，写入3个. 从哪个位置开始读取</span></span><br><span class="line"><span class="comment">    fs.read(fd, buffer, 0, BUFFER_SIZE, 0, function (err, bytesRead) &#123; // bytesRead 真实读取到的个数</span></span><br><span class="line"><span class="comment">        fs.open(path.resolve(__dirname, &#x27;test1&#x27;), &#x27;w&#x27;, function (err, wfd) &#123;</span></span><br><span class="line"><span class="comment">            fs.write(wfd, buffer, 0, bytesRead, 0, function (err, written) &#123; //  written 真正写入的个数</span></span><br><span class="line"><span class="comment">                console.log(written)</span></span><br><span class="line"><span class="comment">            &#125;)</span></span><br><span class="line"><span class="comment">        &#125;)</span></span><br><span class="line"><span class="comment">    &#125;)</span></span><br><span class="line"><span class="comment">&#125;) */</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">copy</span>(<span class="params">source, target, cb</span>) &#123;</span><br><span class="line">    <span class="keyword">const</span> <span class="variable constant_">BUFFER_SIZE</span> = <span class="number">3</span>;</span><br><span class="line">    <span class="keyword">const</span> buffer = <span class="title class_">Buffer</span>.<span class="title function_">alloc</span>(<span class="variable constant_">BUFFER_SIZE</span>);</span><br><span class="line">    fs.<span class="title function_">open</span>(source, <span class="string">&#x27;r&#x27;</span>, <span class="keyword">function</span> (<span class="params">err, fd</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (err) <span class="keyword">return</span> <span class="title function_">cb</span>(err)</span><br><span class="line">        fs.<span class="title function_">open</span>(target, <span class="string">&#x27;w&#x27;</span>, <span class="keyword">function</span> (<span class="params">err, wfd</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (err) <span class="keyword">return</span> <span class="title function_">cb</span>(err)</span><br><span class="line">            <span class="keyword">let</span> readOffset = <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">let</span> writeOffset = <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">function</span> <span class="title function_">next</span>(<span class="params"></span>) &#123;</span><br><span class="line">                fs.<span class="title function_">read</span>(fd, buffer, <span class="number">0</span>, <span class="variable constant_">BUFFER_SIZE</span>, readOffset, <span class="keyword">function</span> (<span class="params">err, bytesRead</span>) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (err) <span class="keyword">return</span> <span class="title function_">cb</span>(err)</span><br><span class="line">                    <span class="keyword">if</span> (bytesRead == <span class="number">0</span>) &#123;</span><br><span class="line">                        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;copy完整&#x27;</span>)</span><br><span class="line">                        fs.<span class="title function_">close</span>(fd, <span class="keyword">function</span> (<span class="params"></span>) &#123; &#125;)</span><br><span class="line">                        fs.<span class="title function_">close</span>(wfd, <span class="keyword">function</span> (<span class="params"></span>) &#123; &#125;)</span><br><span class="line">                        <span class="keyword">return</span></span><br><span class="line">                    &#125;</span><br><span class="line">                    fs.<span class="title function_">write</span>(wfd, buffer, <span class="number">0</span>, bytesRead, writeOffset, <span class="keyword">function</span> (<span class="params">err, written</span>) &#123;</span><br><span class="line">                        <span class="keyword">if</span> (err) <span class="keyword">return</span> <span class="title function_">cb</span>(err)</span><br><span class="line">                        readOffset += written</span><br><span class="line">                        writeOffset = readOff<span class="keyword">set</span></span><br><span class="line">                        <span class="title function_">next</span>();</span><br><span class="line">                    &#125;)</span><br><span class="line">                &#125;)</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="title function_">next</span>()</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 问题？回调地狱   出错了不能统一处理  没法控制暂停  读写没有分离  读写的打开顺序（不应该有顺序）</span></span><br><span class="line"><span class="comment">// 发布订阅来解耦代码</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>ReadStream</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title class_">EventEmitter</span> = <span class="built_in">require</span>(<span class="string">&#x27;events&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>)</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">ReadStream</span> <span class="keyword">extends</span> <span class="title class_ inherited__">EventEmitter</span> &#123;</span><br><span class="line">    <span class="title function_">constructor</span>(<span class="params">path, options = &#123;&#125;</span>) &#123;</span><br><span class="line">        <span class="variable language_">super</span>()</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">path</span> = path;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">flags</span> = options.<span class="property">flags</span> || <span class="string">&#x27;r&#x27;</span>;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">encoding</span> = options.<span class="property">encoding</span> || <span class="literal">null</span>;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">emitClose</span> = options.<span class="property">emitClose</span> || <span class="literal">false</span>;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">start</span> = options.<span class="property">start</span> || <span class="number">0</span>;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">end</span> = options.<span class="property">end</span>;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">highWaterMark</span> = options.<span class="property">highWaterMark</span> || <span class="number">64</span> * <span class="number">1024</span>;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="title function_">open</span>();</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">flowing</span> = <span class="literal">false</span>;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="title function_">on</span>(<span class="string">&#x27;newListener&#x27;</span>, <span class="function">(<span class="params">type</span>) =&gt;</span> &#123; <span class="comment">// events</span></span><br><span class="line">            <span class="keyword">if</span> (type == <span class="string">&#x27;data&#x27;</span>) &#123;</span><br><span class="line">                <span class="variable language_">this</span>.<span class="property">flowing</span> = <span class="literal">true</span>;</span><br><span class="line">                <span class="variable language_">this</span>.<span class="title function_">read</span>(); <span class="comment">// 同步调用read</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">offset</span> = <span class="variable language_">this</span>.<span class="property">start</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">resume</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (!<span class="variable language_">this</span>.<span class="property">flowing</span>) &#123;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">flowing</span> = <span class="literal">true</span>; <span class="comment">// 恢复流动模式</span></span><br><span class="line">            <span class="variable language_">this</span>.<span class="title function_">read</span>();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">pause</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">flowing</span> = <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">read</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="comment">// fs.read()</span></span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">typeof</span> <span class="variable language_">this</span>.<span class="property">fd</span> !== <span class="string">&#x27;number&#x27;</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="title function_">once</span>(<span class="string">&#x27;open&#x27;</span>, <span class="function">() =&gt;</span> <span class="variable language_">this</span>.<span class="title function_">read</span>())</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">const</span> howMuchToRead = <span class="variable language_">this</span>.<span class="property">end</span> ? <span class="title class_">Math</span>.<span class="title function_">min</span>(<span class="variable language_">this</span>.<span class="property">end</span> - <span class="variable language_">this</span>.<span class="property">offset</span> + <span class="number">1</span>, <span class="variable language_">this</span>.<span class="property">highWaterMark</span>) : <span class="variable language_">this</span>.<span class="property">highWaterMark</span></span><br><span class="line">        <span class="keyword">let</span> buffer = <span class="title class_">Buffer</span>.<span class="title function_">alloc</span>(howMuchToRead);</span><br><span class="line">        fs.<span class="title function_">read</span>(<span class="variable language_">this</span>.<span class="property">fd</span>, buffer, <span class="number">0</span>, buffer.<span class="property">length</span>, <span class="variable language_">this</span>.<span class="property">offset</span>, <span class="function">(<span class="params">err, bytesRead</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (bytesRead) &#123;</span><br><span class="line">                <span class="comment">// 我们预期的buffer是100个字节 但是真实读取到的只有6个</span></span><br><span class="line">                <span class="variable language_">this</span>.<span class="title function_">emit</span>(<span class="string">&#x27;data&#x27;</span>, buffer.<span class="title function_">slice</span>(<span class="number">0</span>, bytesRead));</span><br><span class="line">                <span class="variable language_">this</span>.<span class="property">offset</span> += bytesRead;</span><br><span class="line">                <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">flowing</span>) &#123;</span><br><span class="line">                    <span class="variable language_">this</span>.<span class="title function_">read</span>();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="variable language_">this</span>.<span class="title function_">emit</span>(<span class="string">&#x27;end&#x27;</span>);</span><br><span class="line">                <span class="variable language_">this</span>.<span class="title function_">destroy</span>();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">destroy</span>(<span class="params">err</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (err) &#123;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="title function_">emit</span>(<span class="string">&#x27;error&#x27;</span>, err)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">fd</span>) &#123;</span><br><span class="line">            fs.<span class="title function_">close</span>(<span class="variable language_">this</span>.<span class="property">fd</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">                <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">emitClose</span>) &#123;</span><br><span class="line">                    <span class="variable language_">this</span>.<span class="title function_">emit</span>(<span class="string">&#x27;close&#x27;</span>)</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">open</span>(<span class="params"></span>) &#123;</span><br><span class="line">        fs.<span class="title function_">open</span>(<span class="variable language_">this</span>.<span class="property">path</span>, <span class="variable language_">this</span>.<span class="property">flags</span>, <span class="function">(<span class="params">err, fd</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (err) <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="title function_">destroy</span>(err);</span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">fd</span> = fd;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="title function_">emit</span>(<span class="string">&#x27;open&#x27;</span>, fd)</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">pipe</span>(<span class="params">ws</span>) &#123;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="title function_">on</span>(<span class="string">&#x27;data&#x27;</span>, <span class="function"><span class="params">data</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">let</span> flag = ws.<span class="title function_">write</span>(data);</span><br><span class="line">            <span class="keyword">if</span> (!flag) &#123;</span><br><span class="line">                <span class="variable language_">this</span>.<span class="title function_">pause</span>();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;)</span><br><span class="line">        <span class="variable language_">this</span>.<span class="title function_">on</span>(<span class="string">&#x27;end&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">            ws.<span class="title function_">end</span>(); <span class="comment">// 已经写入完毕了</span></span><br><span class="line">        &#125;)</span><br><span class="line">        ws.<span class="title function_">on</span>(<span class="string">&#x27;drain&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="title function_">resume</span>();</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = <span class="title class_">ReadStream</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>ReadStream</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1.</span></span><br><span class="line"><span class="comment">// 基于“文件”系统的可读流</span></span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> <span class="title class_">ReadStream</span> = <span class="built_in">require</span>(<span class="string">&#x27;./ReadStream&#x27;</span>)</span><br><span class="line"><span class="keyword">let</span> rs = <span class="keyword">new</span> <span class="title class_">ReadStream</span>(path.<span class="title function_">resolve</span>(__dirname, <span class="string">&#x27;test&#x27;</span>), &#123;</span><br><span class="line">    <span class="comment">// let rs = fs.createReadStream(path.resolve(__dirname, &#x27;test&#x27;), &#123;</span></span><br><span class="line">    <span class="attr">flags</span>: <span class="string">&#x27;r&#x27;</span>,<span class="comment">// 默认flags就是r 表示读取操作</span></span><br><span class="line">    <span class="attr">encoding</span>: <span class="literal">null</span>, <span class="comment">// 默认读取出的数据是二进制格式</span></span><br><span class="line">    <span class="attr">emitClose</span>: <span class="literal">true</span>,<span class="comment">// 读取完毕后是否要触发close事件</span></span><br><span class="line">    <span class="attr">start</span>: <span class="number">0</span>, <span class="comment">// 从哪里开始读取</span></span><br><span class="line">    <span class="attr">end</span>: <span class="number">3</span>, <span class="comment">// 读取到什么位置 （包后 0-3是四个字节）</span></span><br><span class="line">    <span class="attr">highWaterMark</span>: <span class="number">3</span>, <span class="comment">// 每次读取文件的字节数 64*1024</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// 自己的权限  我所在组的权限 别人的权限  chmod -R 777</span></span><br><span class="line"><span class="comment">// rwxr-xr-x  权限   r 4 w 2 x 1  666</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 文件的可读流才具备open事件</span></span><br><span class="line">rs.<span class="title function_">on</span>(<span class="string">&#x27;open&#x27;</span>, <span class="keyword">function</span> (<span class="params">fd</span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(fd)</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">rs.<span class="title function_">on</span>(<span class="string">&#x27;error&#x27;</span>, <span class="keyword">function</span> (<span class="params">err</span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(err)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">let</span> arr = []</span><br><span class="line">rs.<span class="title function_">on</span>(<span class="string">&#x27;data&#x27;</span>, <span class="keyword">function</span> (<span class="params">data</span>) &#123; <span class="comment">// [123]</span></span><br><span class="line">    arr.<span class="title function_">push</span>(data);</span><br><span class="line">    rs.<span class="title function_">pause</span>();</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(data, <span class="number">29</span>);</span><br><span class="line">&#125;)</span><br><span class="line">rs.<span class="title function_">on</span>(<span class="string">&#x27;end&#x27;</span>, <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title class_">Buffer</span>.<span class="title function_">concat</span>(arr).<span class="title function_">toString</span>());</span><br><span class="line">&#125;);</span><br><span class="line">rs.<span class="title function_">on</span>(<span class="string">&#x27;close&#x27;</span>, <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;close&#x27;</span>)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="built_in">setInterval</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    rs.<span class="title function_">resume</span>(); <span class="comment">// 恢复data的触发</span></span><br><span class="line">    <span class="comment">//   rs.pause(); //  这个暂停意味着不在触发 data事件</span></span><br><span class="line">&#125;, <span class="number">1000</span>)</span><br><span class="line"><span class="comment">/* </span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">// 如果用户监听了data事件，会将数据不停的发射出来</span></span><br><span class="line"><span class="comment">let arr = []</span></span><br><span class="line"><span class="comment">rs.on(&#x27;data&#x27;, function (data) &#123;</span></span><br><span class="line"><span class="comment">    arr.push(data)</span></span><br><span class="line"><span class="comment">&#125;)</span></span><br><span class="line"><span class="comment">rs.on(&#x27;end&#x27;, function () &#123;</span></span><br><span class="line"><span class="comment">    console.log(Buffer.concat(arr).toString());</span></span><br><span class="line"><span class="comment">&#125;);</span></span><br><span class="line"><span class="comment">rs.on(&#x27;error&#x27;, function (err) &#123;</span></span><br><span class="line"><span class="comment">    console.log(err)</span></span><br><span class="line"><span class="comment">&#125;)</span></span><br><span class="line"><span class="comment">// 文件的可读流才具备close事件</span></span><br><span class="line"><span class="comment">rs.on(&#x27;close&#x27;, function () &#123;</span></span><br><span class="line"><span class="comment">    console.log(&#x27;close&#x27;)</span></span><br><span class="line"><span class="comment">&#125;)</span></span><br><span class="line"><span class="comment">// setTimeout(() =&gt; &#123;</span></span><br><span class="line"><span class="comment">//     rs.resume(); // 恢复data的触发</span></span><br><span class="line"><span class="comment">//     rs.pause(); //  这个暂停意味着不在触发 data事件</span></span><br><span class="line"><span class="comment">// &#125;, 1000)</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">// on(&#x27;open&#x27;) on(&#x27;close&#x27;)  on(&#x27;data&#x27;) on(&#x27;end&#x27;)  on(&#x27;error&#x27;)  .pause() .resume() */</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 2.</span></span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>)</span><br><span class="line"><span class="keyword">let</span> rs = fs.<span class="title function_">createReadStream</span>(path.<span class="title function_">resolve</span>(__dirname, <span class="string">&#x27;test&#x27;</span>));</span><br><span class="line"></span><br><span class="line"><span class="comment">// 调试可读流内部原理</span></span><br><span class="line"><span class="comment">// rs.on(&#x27;data&#x27;, function (data) &#123;</span></span><br><span class="line"><span class="comment">//     console.log(data, 29);</span></span><br><span class="line"><span class="comment">// &#125;)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 内部继承了一个类 Readable 父类  new ReadStream 是Readable子类</span></span><br><span class="line"><span class="comment">// ReflectApply(Readable, this, [options]);   Readable.call(this)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// ObjectSetPrototypeOf(ReadStream.prototype, Readable.prototype); 子类继承父类的原型方法</span></span><br><span class="line"><span class="comment">// 父类提供了一个Readable.prototype.read方法 （内部会检测用户监听了data事件） 就会调用read方法</span></span><br><span class="line"><span class="comment">// 父类调用子类的this._read， 内部采用的是 fs.read方法来进行读取的</span></span><br><span class="line"><span class="comment">// 将读取的数据调用 this.push()  -&gt; this.emit(&#x27;data&#x27;,chunk)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 我们可以自定义可读流</span></span><br><span class="line"><span class="keyword">let</span> clientData = <span class="string">&#x27;hello world&#x27;</span></span><br><span class="line"><span class="keyword">const</span> &#123; <span class="title class_">Readable</span> &#125; = <span class="built_in">require</span>(<span class="string">&#x27;stream&#x27;</span>)</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">MyReadStream</span> <span class="keyword">extends</span> <span class="title class_ inherited__">Readable</span> &#123;</span><br><span class="line">    <span class="title function_">_read</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="title function_">push</span>(clientData);</span><br><span class="line">        <span class="variable language_">this</span>.<span class="title function_">push</span>(<span class="literal">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> mrs = <span class="keyword">new</span> <span class="title class_">MyReadStream</span>();</span><br><span class="line"><span class="comment">// 不具备 close open 方法， 因为不是文件</span></span><br><span class="line">mrs.<span class="title function_">on</span>(<span class="string">&#x27;data&#x27;</span>, <span class="keyword">function</span> (<span class="params">data</span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(data);</span><br><span class="line">&#125;)</span><br><span class="line">mrs.<span class="title function_">on</span>(<span class="string">&#x27;end&#x27;</span>, <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;结束&#x27;</span>)</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 以后见到能on(&#x27;data&#x27;) on(&#x27;end&#x27;) 一定是一个可读流</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 3.</span></span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>);</span><br><span class="line"><span class="keyword">let</span> ws = fs.<span class="title function_">createWriteStream</span>(path.<span class="title function_">resolve</span>(__dirname, <span class="string">&#x27;test1&#x27;</span>), &#123;</span><br><span class="line">    <span class="attr">flags</span>: <span class="string">&#x27;w&#x27;</span>, <span class="comment">// fs.open()</span></span><br><span class="line">    <span class="attr">encoding</span>: <span class="string">&#x27;utf8&#x27;</span>, <span class="comment">// 编码格式  （一个文件能写一半gbk和一半utf8）</span></span><br><span class="line">    <span class="attr">mode</span>: <span class="number">438</span>,</span><br><span class="line">    <span class="attr">start</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">highWaterMark</span>: <span class="number">3</span> <span class="comment">// （读取的时候 代表每次能读取多少个，但是写入的时候表示的是我期望使用的内存大小</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 每次open的时候 会清空文件</span></span><br><span class="line"><span class="comment">// 可写流有三个方法 write()  write.end()  </span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> flag = ws.<span class="title function_">write</span>(<span class="string">&#x27;ok&#x27;</span>); <span class="comment">// fs.write 如何解决多个异步的并发问题</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(flag)</span><br><span class="line">flag = ws.<span class="title function_">write</span>(<span class="string">&#x27;o&#x27;</span>);</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(flag)</span><br><span class="line"></span><br><span class="line"><span class="comment">// drain事件有一个触发条件 就是需要保证达到预期后清空内存才会触发</span></span><br><span class="line">ws.<span class="title function_">on</span>(<span class="string">&#x27;drain&#x27;</span>, <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;diran&#x27;</span>, <span class="string">&#x27;都写入成功了&#x27;</span>);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 4.</span></span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>);</span><br><span class="line"><span class="comment">// const WriteStream = require(&#x27;./WriteStream&#x27;);</span></span><br><span class="line"><span class="comment">// // let ws = new WriteStream(path.resolve(__dirname, &#x27;test1&#x27;), &#123;</span></span><br><span class="line"><span class="comment">// let ws = fs.createWriteStream(path.resolve(__dirname, &#x27;test1&#x27;), &#123;</span></span><br><span class="line"><span class="comment">//     flags: &#x27;w&#x27;,</span></span><br><span class="line"><span class="comment">//     encoding: &#x27;utf8&#x27;,</span></span><br><span class="line"><span class="comment">//     mode: 438,</span></span><br><span class="line"><span class="comment">//     start: 0,</span></span><br><span class="line"><span class="comment">//     highWaterMark: 3</span></span><br><span class="line"><span class="comment">// &#125;);</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// let flag = ws.write(&#x27;ok&#x27;);</span></span><br><span class="line"><span class="comment">// flag = ws.write(&#x27;o&#x27;);</span></span><br><span class="line"><span class="comment">// flag = ws.write(&#x27;k&#x27;);</span></span><br><span class="line"><span class="comment">// ws.on(&#x27;drain&#x27;, function () &#123;</span></span><br><span class="line"><span class="comment">//     console.log(&#x27;diran&#x27;, &#x27;都写入成功了&#x27;);</span></span><br><span class="line"><span class="comment">//     // let flag = ws.write(&#x27;ok&#x27;);</span></span><br><span class="line"><span class="comment">// &#125;);</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// ws.end(&#x27;哈哈&#x27;) // = write + close</span></span><br><span class="line"><span class="comment">// 1） 为了实现可以对可写流的扩展  WriteStream 继承于父类 Writable</span></span><br><span class="line"><span class="comment">// 2) 父类有一个方法write()  子类有一个方法_write  this._write</span></span><br><span class="line"><span class="keyword">const</span> &#123; <span class="title class_">Writable</span>, <span class="title class_">Duplex</span> &#125; = <span class="built_in">require</span>(<span class="string">&#x27;stream&#x27;</span>)</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">MyWriteStream</span> <span class="keyword">extends</span> <span class="title class_ inherited__">Duplex</span> &#123;</span><br><span class="line">    <span class="title function_">constructor</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="variable language_">super</span>(&#123; <span class="attr">highWaterMark</span>: <span class="number">2</span> &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">_read</span>(<span class="params"></span>) &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">_write</span>(<span class="params">data, encoding, clearBuffer</span>) &#123; <span class="comment">// callback -》 clearBuffer</span></span><br><span class="line">        <span class="comment">// fs.write()</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(data)</span><br><span class="line">        <span class="title function_">clearBuffer</span>()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> ms = <span class="keyword">new</span> <span class="title class_">MyWriteStream</span>();</span><br><span class="line">ms.<span class="title function_">write</span>(<span class="string">&#x27;ok&#x27;</span>); <span class="comment">// 只有第一次调用write会正在的写入到文件中 _write</span></span><br><span class="line">ms.<span class="title function_">write</span>(<span class="string">&#x27;ok&#x27;</span>)</span><br><span class="line">ms.<span class="title function_">write</span>(<span class="string">&#x27;ok&#x27;</span>)</span><br><span class="line"></span><br><span class="line">ms.<span class="title function_">on</span>(<span class="string">&#x27;drain&#x27;</span>, <span class="keyword">function</span> (<span class="params"></span>) &#123; <span class="comment">//  drain 是WriteStream里面实现的</span></span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;drain&#x27;</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>
</li>
<li><p>pipe</p>
</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>);</span><br><span class="line"><span class="keyword">let</span> rs = fs.<span class="title function_">createReadStream</span>(path.<span class="title function_">resolve</span>(__dirname, <span class="string">&#x27;test&#x27;</span>), &#123;</span><br><span class="line">    <span class="attr">highWaterMark</span>: <span class="number">4</span> <span class="comment">// 每次读取4个</span></span><br><span class="line">&#125;);</span><br><span class="line"><span class="keyword">let</span> ws = fs.<span class="title function_">createWriteStream</span>(path.<span class="title function_">resolve</span>(__dirname, <span class="string">&#x27;test1&#x27;</span>), &#123; <span class="comment">//  createWriteStream 有缓存的概念</span></span><br><span class="line">    <span class="attr">highWaterMark</span>: <span class="number">1</span> <span class="comment">// 我期望使用一个字节的内存大小来控制</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// pipe</span></span><br><span class="line"></span><br><span class="line">rs.<span class="title function_">pipe</span>(ws); <span class="comment">// 看不到写入的过程， 此方法是异步的方法</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* </span></span><br><span class="line"><span class="comment">rs.on(&#x27;data&#x27;, function (data) &#123;</span></span><br><span class="line"><span class="comment">    let flag = ws.write(data);</span></span><br><span class="line"><span class="comment">    if (!flag) &#123; // 已经超过我的预期了，再给我会浪费内存，先别读取</span></span><br><span class="line"><span class="comment">        rs.pause();</span></span><br><span class="line"><span class="comment">    &#125;</span></span><br><span class="line"><span class="comment">&#125;)</span></span><br><span class="line"><span class="comment">ws.on(&#x27;drain&#x27;, function () &#123;</span></span><br><span class="line"><span class="comment">    console.log(&#x27;分段读取&#x27;)</span></span><br><span class="line"><span class="comment">    rs.resume(); // 回复继续读取，继续触发data事件</span></span><br><span class="line"><span class="comment">&#125;) */</span></span><br></pre></td></tr></table></figure>

<ul>
<li><p>process</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 监听进程的标准输入， 用户可以和命令行做交互操作</span></span><br><span class="line"><span class="comment">// 初始化一个项目 需要用户输入用户名称：</span></span><br><span class="line"><span class="comment">// process.stdin.on(&#x27;data&#x27;, function (data) &#123; // 可以用于进程间的通信。 可以用于进程间的交互 </span></span><br><span class="line"><span class="comment">//     // console.log(data)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//     // 标准输出和console.log功能一样</span></span><br><span class="line"><span class="comment">//     // 错误输出 console.err</span></span><br><span class="line"><span class="comment">//     process.stderr.write(data); // 可写流</span></span><br><span class="line"><span class="comment">// &#125;);</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 压缩流、加密的流 </span></span><br><span class="line"></span><br><span class="line"><span class="comment">// a  -&gt; 转化过程（转化流）  -&gt; b</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> &#123; <span class="title class_">Transform</span> &#125; = <span class="built_in">require</span>(<span class="string">&#x27;stream&#x27;</span>)</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">MyTransform</span> <span class="keyword">extends</span> <span class="title class_ inherited__">Transform</span> &#123;</span><br><span class="line">    <span class="title function_">_transform</span>(<span class="params">chunk, encoding, clearBuffer</span>) &#123;<span class="comment">// 具备_write的参数 也具备可读流的push方法</span></span><br><span class="line">        <span class="variable language_">this</span>.<span class="title function_">push</span>(chunk.<span class="title function_">toString</span>().<span class="title function_">toUpperCase</span>())</span><br><span class="line">        <span class="title function_">clearBuffer</span>();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> transform = <span class="keyword">new</span> <span class="title class_">MyTransform</span>()</span><br><span class="line"></span><br><span class="line">process.<span class="property">stdin</span>.<span class="title function_">pipe</span>(transform).<span class="title function_">pipe</span>(process.<span class="property">stdout</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 文件的可读流和可写流 （解耦，异步并发  fs.createReadStream(on(&#x27;data&#x27;) on(&#x27;end&#x27;)) writeStream(write end) ）</span></span><br><span class="line"><span class="comment">// 怎么实现自定义的流  思想</span></span><br><span class="line"><span class="comment">// pipe 方法的实现是一个边读编写的过程</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 文件夹操作，tcp 和 http </span></span><br></pre></td></tr></table></figure>
</li>
<li><p>writeStream</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title class_">EventEmitter</span> = <span class="built_in">require</span>(<span class="string">&#x27;events&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">WriteStream</span> <span class="keyword">extends</span> <span class="title class_ inherited__">EventEmitter</span> &#123;</span><br><span class="line">    <span class="title function_">constructor</span>(<span class="params">path, options = &#123;&#125;</span>) &#123;</span><br><span class="line">        <span class="variable language_">super</span>();</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">path</span> = path;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">flags</span> = options.<span class="property">flags</span>;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">encoding</span> = options.<span class="property">encoding</span> || <span class="string">&#x27;utf8&#x27;</span>;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">mode</span> = options.<span class="property">mode</span> || <span class="number">438</span>;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">start</span> = options.<span class="property">start</span> || <span class="number">0</span>;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">highWaterMark</span> = options.<span class="property">highWaterMark</span> || <span class="number">16</span> * <span class="number">1024</span>;</span><br><span class="line"></span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">len</span> = <span class="number">0</span>; <span class="comment">// 维护写入的个数和长度</span></span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">writing</span> = <span class="literal">false</span>; <span class="comment">// 是否正在写入来区分放到缓存区还是写入文件中</span></span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">cache</span> = []; <span class="comment">// 用于缓存除了第一次写入的逻辑</span></span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">needDrain</span> = <span class="literal">false</span>; <span class="comment">// 是否要触发drain事件</span></span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">offset</span> = <span class="variable language_">this</span>.<span class="property">start</span>; <span class="comment">// 写入的偏移量</span></span><br><span class="line">        <span class="variable language_">this</span>.<span class="title function_">open</span>();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="title function_">end</span>(<span class="params">chunk = <span class="string">&#x27;&#x27;</span>, encoding = <span class="variable language_">this</span>.encoding, callback = () =&gt; &#123; &#125;</span>) &#123;</span><br><span class="line">        chunk = <span class="title class_">Buffer</span>.<span class="title function_">isBuffer</span>(chunk) ? chunk : <span class="title class_">Buffer</span>.<span class="title function_">from</span>(chunk);</span><br><span class="line">        <span class="variable language_">this</span>.<span class="title function_">write</span>(chunk, encoding, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">needDrain</span> = <span class="literal">false</span>;</span><br><span class="line">            <span class="title function_">callback</span>();</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">clearBuffer</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">let</span> cur = <span class="variable language_">this</span>.<span class="property">cache</span>.<span class="title function_">shift</span>(); <span class="comment">// 在队列中拿出第一个</span></span><br><span class="line">        <span class="keyword">if</span> (cur) &#123;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="title function_">_write</span>(cur.<span class="property">chunk</span>, cur.<span class="property">encoding</span>, cur.<span class="property">callback</span>)</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// 是否要触发drain事件</span></span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">writing</span> = <span class="literal">false</span>; <span class="comment">// 触发drain的时候 下次写入可以在向文件中继续写入</span></span><br><span class="line">            <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">needDrain</span>) &#123;</span><br><span class="line">                <span class="variable language_">this</span>.<span class="property">needDrain</span> = <span class="literal">false</span>;</span><br><span class="line">                <span class="variable language_">this</span>.<span class="title function_">emit</span>(<span class="string">&#x27;drain&#x27;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">write</span>(<span class="params">chunk, encoding = <span class="variable language_">this</span>.encoding, callback = () =&gt; &#123; &#125;</span>) &#123;</span><br><span class="line">        <span class="comment">// 统一写入的数据格式</span></span><br><span class="line">        chunk = <span class="title class_">Buffer</span>.<span class="title function_">isBuffer</span>(chunk) ? chunk : <span class="title class_">Buffer</span>.<span class="title function_">from</span>(chunk);</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">len</span> += chunk.<span class="property">length</span>;</span><br><span class="line">        <span class="keyword">let</span> returnValue = <span class="variable language_">this</span>.<span class="property">len</span> &lt; <span class="variable language_">this</span>.<span class="property">highWaterMark</span>;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">needDrain</span> = !returnValue; <span class="comment">// 如果写入的数据达到了预期才应该触发needDrain</span></span><br><span class="line">        <span class="keyword">const</span> <span class="title function_">clear</span> = (<span class="params"></span>) =&gt; &#123;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="title function_">clearBuffer</span>();</span><br><span class="line">            <span class="title function_">callback</span>();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">writing</span>) &#123;</span><br><span class="line">            <span class="comment">// 向缓存中写入</span></span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">cache</span>.<span class="title function_">push</span>(&#123;</span><br><span class="line">                chunk,</span><br><span class="line">                encoding,</span><br><span class="line">                <span class="attr">callback</span>: clear</span><br><span class="line">            &#125;); <span class="comment">// 多个异步同时操作 可以采用队列的方式来记录</span></span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">writing</span> = <span class="literal">true</span>;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="title function_">_write</span>(chunk, encoding, clear);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> returnValue</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">_write</span>(<span class="params">chunk, encoding, callback</span>) &#123;</span><br><span class="line">        <span class="comment">// 调用fs.write写入</span></span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">typeof</span> <span class="variable language_">this</span>.<span class="property">fd</span> !== <span class="string">&#x27;number&#x27;</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="title function_">once</span>(<span class="string">&#x27;open&#x27;</span>, <span class="function">() =&gt;</span> <span class="variable language_">this</span>.<span class="title function_">_write</span>(chunk, encoding, callback))</span><br><span class="line">        &#125;</span><br><span class="line">        fs.<span class="title function_">write</span>(<span class="variable language_">this</span>.<span class="property">fd</span>, chunk, <span class="number">0</span>, chunk.<span class="property">length</span>, <span class="variable language_">this</span>.<span class="property">offset</span>, <span class="function">(<span class="params">err, written</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">len</span> -= written; <span class="comment">// 写入后 减少正在写入的个数</span></span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">offset</span> += written;</span><br><span class="line">            <span class="title function_">callback</span>();</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">open</span>(<span class="params"></span>) &#123;</span><br><span class="line">        fs.<span class="title function_">open</span>(<span class="variable language_">this</span>.<span class="property">path</span>, <span class="variable language_">this</span>.<span class="property">flags</span>, <span class="variable language_">this</span>.<span class="property">mode</span>, <span class="function">(<span class="params">error, fd</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (error) <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="title function_">destroy</span>(error);</span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">fd</span> = fd;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="title function_">emit</span>(<span class="string">&#x27;open&#x27;</span>, fd)</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">destroy</span>(<span class="params">err</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (err) &#123;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="title function_">emit</span>(<span class="string">&#x27;error&#x27;</span>, err)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">fd</span>) &#123;</span><br><span class="line">            fs.<span class="title function_">close</span>(<span class="variable language_">this</span>.<span class="property">fd</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">                <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">emitClose</span>) &#123;</span><br><span class="line">                    <span class="variable language_">this</span>.<span class="title function_">emit</span>(<span class="string">&#x27;close&#x27;</span>)</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = <span class="title class_">WriteStream</span></span><br></pre></td></tr></table></figure></li>
</ul>

      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/wieldy/bailment-blog/2022/03/29/stream/" data-id="cljmgj1f0000ozc9j0m2f1xhm" data-title="stream" class="article-share-link">Share</a>
      
      
      
    </footer>
  </div>
  
</article>



  
    <article id="post-vue3-1.reactivity" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/bailment-blog/2022/03/29/vue3-1.reactivity/" class="article-date">
  <time class="dt-published" datetime="2022-03-29T14:12:00.000Z" itemprop="datePublished">2022-03-29</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="p-name article-title" href="/bailment-blog/2022/03/29/vue3-1.reactivity/">1.reactivity</a>
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <ul>
<li><p>shared&#x2F;src&#x2F;index.ts</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> <span class="title function_">isObject</span> = (<span class="params">value</span>) =&gt;&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">typeof</span> value === <span class="string">&#x27;object&#x27;</span> &amp;&amp; value !== <span class="literal">null</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> <span class="title function_">isFunction</span>= (<span class="params">value</span>) =&gt;&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">typeof</span> value === <span class="string">&#x27;function&#x27;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>基本使用</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;IE=edge&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- &lt;script src=&quot;../../../node_modules/@vue/reactivity/dist/reactivity.global.js&quot;&gt;&lt;/script&gt; --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;./reactivity.global.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;app&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// 缓存代理结果 require()</span></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">const</span> &#123;effect ,reactive&#125; = <span class="title class_">VueReactivity</span>;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// 会对属性进行劫持 proxy， 监听用户的获取操作和设置操作</span></span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">const</span> obj = &#123;<span class="attr">name</span>:<span class="string">&#x27;zf&#x27;</span>,<span class="attr">age</span>:<span class="number">13</span>, <span class="attr">address</span>:&#123;<span class="attr">num</span>:<span class="number">30</span>&#125;,<span class="attr">flag</span>:<span class="literal">true</span>&#125;</span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">const</span> state = <span class="title function_">reactive</span>(obj); <span class="comment">// 只能传入对象， 因为proxy 只支持对象格式</span></span></span><br><span class="line"><span class="language-javascript">        </span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// effect 函数默认会执行一次， 后续数据变化了会重新执行effect函数</span></span></span><br><span class="line"><span class="language-javascript">        <span class="title function_">effect</span>(<span class="function">()=&gt;</span>&#123;</span></span><br><span class="line"><span class="language-javascript">            app.<span class="property">innerHTML</span> = state.<span class="property">name</span> + <span class="string">&#x27;今年&#x27;</span> + state.<span class="property">age</span> + <span class="string">&#x27;岁了门牌号是 &#x27;</span>+ state.<span class="property">address</span>.<span class="property">num</span></span></span><br><span class="line"><span class="language-javascript">        &#125;)</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="built_in">setTimeout</span>(<span class="function">()=&gt;</span>&#123;</span></span><br><span class="line"><span class="language-javascript">            state.<span class="property">age</span>++</span></span><br><span class="line"><span class="language-javascript">        &#125;,<span class="number">1000</span>)</span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// effect()  -&gt; effect()</span></span></span><br><span class="line"><span class="language-javascript">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>reactivity</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reactive.ts</span></span><br><span class="line"><span class="keyword">import</span> &#123; isObject &#125; <span class="keyword">from</span> <span class="string">&quot;@vue/shared&quot;</span>;</span><br><span class="line"><span class="keyword">import</span>  &#123; <span class="title class_">ReactiveFlags</span>,baseHandler &#125; <span class="keyword">from</span> <span class="string">&quot;./baseHandler&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> reactiveMap = <span class="keyword">new</span> <span class="title class_">WeakMap</span>();<span class="comment">// key必须是对象，弱引用</span></span><br><span class="line"><span class="comment">// v8的垃圾回收机制  标记删除  引用计数</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> <span class="title function_">reactive</span>(<span class="params">target</span>)&#123;</span><br><span class="line">    <span class="keyword">if</span>(!<span class="title function_">isObject</span>(target))&#123;</span><br><span class="line">        <span class="keyword">return</span> target</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// es6 中的proxy </span></span><br><span class="line">    <span class="keyword">if</span>(target[<span class="title class_">ReactiveFlags</span>.<span class="property">IS_REACTIVE</span>])&#123;</span><br><span class="line">        <span class="keyword">return</span> target</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">const</span> existing = reactiveMap.<span class="title function_">get</span>(target);</span><br><span class="line">    <span class="keyword">if</span>(existing)&#123;</span><br><span class="line">        <span class="keyword">return</span> existing</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">const</span> proxy = <span class="keyword">new</span> <span class="title class_">Proxy</span>(target,baseHandler);</span><br><span class="line">    reactiveMap.<span class="title function_">set</span>(target,proxy)</span><br><span class="line">    <span class="keyword">return</span> proxy;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 一个对象已经被代理过了 ，就不要再次被代理了</span></span><br><span class="line"><span class="comment">// 使用proxy 要搭配Reflect来使用  obj -&gt; proxy</span></span><br><span class="line"><span class="comment">// 下次你传入的是proxy了，我去这个对象上取值可以命中proxy的get方法</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">let person = &#123;</span></span><br><span class="line"><span class="comment">    name:&#x27;zf&#x27;,</span></span><br><span class="line"><span class="comment">    get aliasName()&#123; // 属性访问器</span></span><br><span class="line"><span class="comment">        return this.name + &#x27;jg&#x27;</span></span><br><span class="line"><span class="comment">    &#125;</span></span><br><span class="line"><span class="comment">&#125;</span></span><br><span class="line"><span class="comment">// proxy 一般搭配Reflect来使用</span></span><br><span class="line"><span class="comment">const proxy = new Proxy(person,&#123;</span></span><br><span class="line"><span class="comment">    get(target,key,receiver)&#123;</span></span><br><span class="line"><span class="comment">        console.log(&#x27;这里可以记录这个属性使用了哪个effect&#x27;)</span></span><br><span class="line"><span class="comment">        return Reflect.get(target,key,receiver)</span></span><br><span class="line"><span class="comment">    &#125;,</span></span><br><span class="line"><span class="comment">    set(target,key,value,receiver)&#123;</span></span><br><span class="line"><span class="comment">        console.log(&#x27;这里可以通知effect重新执行&#x27;)</span></span><br><span class="line"><span class="comment">        return Reflect.set(target,key,value,receiver);</span></span><br><span class="line"><span class="comment">    &#125;</span></span><br><span class="line"><span class="comment">&#125;);</span></span><br><span class="line"><span class="comment">// 原因是因为我去proxy上取aliasName,这个时候回执行get方法</span></span><br><span class="line"><span class="comment">// 但是aliasName 是基于name属性 原则上应该去name上取值</span></span><br><span class="line"><span class="comment">// 然而this.name 并没有触发proxy的get，也就意味着稍后我们修改name属性的时候</span></span><br><span class="line"><span class="comment">// 就不会导致页面重新渲染</span></span><br><span class="line"><span class="comment">proxy.aliasName</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>baseHandler</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// baseHandler.ts</span></span><br><span class="line"><span class="keyword">import</span> &#123; isObject &#125; <span class="keyword">from</span> <span class="string">&quot;@vue/shared&quot;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; reactive &#125; <span class="keyword">from</span> <span class="string">&quot;./reactive&quot;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; track, trigger &#125; <span class="keyword">from</span> <span class="string">&quot;./effect&quot;</span>;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> <span class="keyword">enum</span> <span class="title class_">ReactiveFlags</span> &#123;</span><br><span class="line">    <span class="variable constant_">IS_REACTIVE</span> = <span class="string">&#x27;__v_isReactive&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> baseHandler  = &#123;</span><br><span class="line">    <span class="title function_">get</span>(<span class="params">target,key,receiver</span>)&#123;</span><br><span class="line">        <span class="keyword">if</span>(key === <span class="title class_">ReactiveFlags</span>.<span class="property">IS_REACTIVE</span>)&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 让当前的key 和 effect关联起来即可</span></span><br><span class="line">        <span class="title function_">track</span>(target,key);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// lazy proxy</span></span><br><span class="line">        <span class="keyword">let</span> res =  <span class="title class_">Reflect</span>.<span class="title function_">get</span>(target,key,receiver);</span><br><span class="line">        <span class="keyword">if</span>(<span class="title function_">isObject</span>(res))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="title function_">reactive</span>(res) </span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> res</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="title function_">set</span>(<span class="params">target,key,value,receiver</span>)&#123;</span><br><span class="line">        <span class="comment">// 数据变化后，要根据属性找到对应的effect列表让其依次执行</span></span><br><span class="line">        <span class="keyword">let</span> oldValue = target[key];</span><br><span class="line">        <span class="keyword">if</span>(oldValue !== value )&#123;</span><br><span class="line">            <span class="keyword">let</span> result = <span class="title class_">Reflect</span>.<span class="title function_">set</span>(target,key,value,receiver);;</span><br><span class="line">            <span class="title function_">trigger</span>(target,key,value);</span><br><span class="line">            <span class="keyword">return</span> result</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>src&#x2F; 目录下</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// index.ts</span></span><br><span class="line"><span class="keyword">export</span> &#123;effect&#125; <span class="keyword">from</span> <span class="string">&#x27;./effect&#x27;</span>;</span><br><span class="line"><span class="keyword">export</span> &#123;reactive&#125; <span class="keyword">from</span> <span class="string">&#x27;./reactive&#x27;</span>;</span><br><span class="line"><span class="keyword">export</span> &#123;computed&#125; <span class="keyword">from</span> <span class="string">&#x27;./computed&#x27;</span>;</span><br></pre></td></tr></table></figure>
</li>
<li><p>effect.ts</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">let</span> activeEffect = <span class="literal">undefined</span>;</span><br><span class="line"><span class="comment">// 依赖收集的原理是 借助js是单线程的特点， 默认调用effect的时候会去调用proxy的get，此时让属性记住</span></span><br><span class="line"><span class="comment">// 依赖的effect，同理也让effect记住对应的属性</span></span><br><span class="line"><span class="comment">// 靠的是数据结构 weakMap : &#123;map:&#123;key:new Set()&#125;&#125;</span></span><br><span class="line"><span class="comment">// 稍后数据变化的时候 找到对应的map 通过属性出发set中effect</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">cleanEffect</span>(<span class="params">effect</span>) &#123;</span><br><span class="line">    <span class="comment">// 需要清理effect中存入属性中的set中的effect </span></span><br><span class="line">    <span class="comment">// 每次执行前都需要将effect只对应属性的set集合都清理掉</span></span><br><span class="line">    <span class="comment">// 属性中的set 依然存放effect</span></span><br><span class="line">    <span class="keyword">let</span> deps = effect.<span class="property">deps</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; deps.<span class="property">length</span>; i++) &#123;</span><br><span class="line">        deps[i].<span class="title function_">delete</span>(effect)</span><br><span class="line">    &#125;</span><br><span class="line">    effect.<span class="property">deps</span>.<span class="property">length</span> = <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">class</span> <span class="title class_">ReactiveEffect</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> active = <span class="literal">true</span>;</span><br><span class="line">    <span class="keyword">public</span> parent = <span class="literal">null</span>;</span><br><span class="line">    <span class="keyword">public</span> deps = []; <span class="comment">// effect中用了哪些属性，后续清理的时候要使用</span></span><br><span class="line">    <span class="title function_">constructor</span>(<span class="params"><span class="keyword">public</span> fn,<span class="keyword">public</span> scheduler?</span>) &#123; &#125; <span class="comment">// 你传递的fn我会帮你放到this上</span></span><br><span class="line">    <span class="comment">// effectScope 可以来实现让所有的effect停止</span></span><br><span class="line">    <span class="title function_">run</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="comment">// 依赖收集  让属性和effect 产生关联</span></span><br><span class="line">        <span class="keyword">if</span> (!<span class="variable language_">this</span>.<span class="property">active</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="title function_">fn</span>();</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="variable language_">this</span>.<span class="property">parent</span> = activeEffect</span><br><span class="line">                activeEffect = <span class="variable language_">this</span>;</span><br><span class="line">                <span class="title function_">cleanEffect</span>(<span class="variable language_">this</span>); <span class="comment">// vue2 和 vue3中都是要清理的 </span></span><br><span class="line">                <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="title function_">fn</span>(); <span class="comment">// 去proxy对象上取值, 取之的时候 我要让这个熟悉 和当前的effect函数关联起来，稍后数据变化了 ，可以重新执行effect函数</span></span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                <span class="comment">// 取消当前正在运行的effect</span></span><br><span class="line">                activeEffect = <span class="variable language_">this</span>.<span class="property">parent</span>;</span><br><span class="line">                <span class="variable language_">this</span>.<span class="property">parent</span> = <span class="literal">null</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">stop</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">active</span>) &#123;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">active</span> = <span class="literal">false</span>;</span><br><span class="line">            <span class="title function_">cleanEffect</span>(<span class="variable language_">this</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 哪个对象中的那个属性 对应的哪个effect  一个属性可以对应多个effect</span></span><br><span class="line"><span class="comment">// 外层用一个map &#123;object: &#123;name:[effect,effect],age:[effect,effect]&#125;&#125;</span></span><br><span class="line"><span class="keyword">const</span> targetMap = <span class="keyword">new</span> <span class="title class_">WeakMap</span>();</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> <span class="title function_">trigger</span>(<span class="params">target, key, value</span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> depsMap = targetMap.<span class="title function_">get</span>(target);</span><br><span class="line">    <span class="keyword">if</span> (!depsMap) &#123;</span><br><span class="line">        <span class="keyword">return</span>; <span class="comment">// 属性没有依赖任何的effect</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">let</span> effects = depsMap.<span class="title function_">get</span>(key)</span><br><span class="line">    <span class="title function_">triggerEffects</span>(effects)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> <span class="title function_">triggerEffects</span>(<span class="params">effects</span>)&#123;</span><br><span class="line">    <span class="keyword">if</span> (effects) &#123;</span><br><span class="line">        effects = <span class="keyword">new</span> <span class="title class_">Set</span>(effects)</span><br><span class="line">        effects.<span class="title function_">forEach</span>(<span class="function"><span class="params">effect</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (effect !== activeEffect) &#123; <span class="comment">// 保证要执行的effect不是当前的effect</span></span><br><span class="line">                <span class="keyword">if</span>(effect.<span class="property">scheduler</span>)&#123;</span><br><span class="line">                    effect.<span class="title function_">scheduler</span>(); <span class="comment">// 可以提供一个调度函数，用户实现自己的逻辑</span></span><br><span class="line">                &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                    effect.<span class="title function_">run</span>(); <span class="comment">// 数据变化了，找到对应的effect 重新执行</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> <span class="title function_">track</span>(<span class="params">target, key</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (activeEffect) &#123;</span><br><span class="line">        <span class="comment">// 这里搞依赖收集</span></span><br><span class="line">        <span class="keyword">let</span> depsMap = targetMap.<span class="title function_">get</span>(target);</span><br><span class="line">        <span class="keyword">if</span> (!depsMap) &#123;</span><br><span class="line">            targetMap.<span class="title function_">set</span>(target, (depsMap = <span class="keyword">new</span> <span class="title class_">Map</span>()))</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">let</span> deps = depsMap.<span class="title function_">get</span>(key);</span><br><span class="line">        <span class="keyword">if</span> (!deps) &#123;</span><br><span class="line">            depsMap.<span class="title function_">set</span>(key, (deps = <span class="keyword">new</span> <span class="title class_">Set</span>()))</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="title function_">trackEffects</span>(deps)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 让属性记录所用到的effect是谁， 哪个effect对应了哪些属性</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> <span class="title function_">trackEffects</span>(<span class="params">deps</span>)&#123;</span><br><span class="line">    <span class="keyword">let</span> shouldTrack = !deps.<span class="title function_">has</span>(activeEffect);</span><br><span class="line">    <span class="keyword">if</span> (shouldTrack) &#123;</span><br><span class="line">        deps.<span class="title function_">add</span>(activeEffect);</span><br><span class="line">        <span class="comment">// 等等 deps 的作用就是让effect 记录用到了哪些属性</span></span><br><span class="line">        activeEffect.<span class="property">deps</span>.<span class="title function_">push</span>(deps); <span class="comment">// 放的是set </span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> <span class="title function_">effect</span>(<span class="params">fn, options = &#123;&#125; <span class="keyword">as</span> <span class="built_in">any</span></span>) &#123;</span><br><span class="line">    <span class="comment">// 将用户传递的函数编程响应式的effect</span></span><br><span class="line">    <span class="keyword">const</span> _effect = <span class="keyword">new</span> <span class="title class_">ReactiveEffect</span>(fn,options.<span class="property">scheduler</span>);</span><br><span class="line">    <span class="comment">// 更改runner中的this</span></span><br><span class="line">    _effect.<span class="title function_">run</span>()</span><br><span class="line">    <span class="keyword">const</span> runner = _effect.<span class="property">run</span>.<span class="title function_">bind</span>(_effect);</span><br><span class="line">    runner.<span class="property">effect</span> = _effect; <span class="comment">// 暴露effect的实例</span></span><br><span class="line">    <span class="keyword">return</span> runner<span class="comment">// 用户可以手动调用runner重新执行</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// activeEffect = e2;</span></span><br><span class="line"><span class="comment">// effect(()=&gt;&#123; // e1  e1.parent = null</span></span><br><span class="line"><span class="comment">//     state.name;  // name = e1</span></span><br><span class="line"><span class="comment">//     effect(()=&gt;&#123; // e2  e2.parent = e1;</span></span><br><span class="line"><span class="comment">//         state.age; // age = e2</span></span><br><span class="line"><span class="comment">//     &#125;)</span></span><br><span class="line"><span class="comment">//     // activeeffect = e2.parent</span></span><br><span class="line"><span class="comment">//     state.address; // address = e1</span></span><br><span class="line"><span class="comment">// &#125;)</span></span><br><span class="line"></span><br></pre></td></tr></table></figure></li>
</ul>
<!-- computed -->
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// computed.ts</span></span><br><span class="line"><span class="keyword">import</span> &#123; isFunction &#125; <span class="keyword">from</span> <span class="string">&quot;@vue/shared&quot;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; activeEffect, <span class="title class_">ReactiveEffect</span>, track, trackEffects, triggerEffects &#125; <span class="keyword">from</span> <span class="string">&quot;./effect&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> <span class="title function_">computed</span>(<span class="params">getterOrOptions</span>)&#123;</span><br><span class="line">    <span class="keyword">let</span> isGetter = <span class="title function_">isFunction</span>(getterOrOptions);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">let</span> getter;</span><br><span class="line">    <span class="keyword">let</span> setter;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> <span class="title function_">fn</span> = (<span class="params"></span>)=&gt; <span class="variable language_">console</span>.<span class="title function_">warn</span>(<span class="string">&#x27;computed is readonly &#x27;</span>);</span><br><span class="line">    <span class="keyword">if</span>(isGetter)&#123;</span><br><span class="line">        getter = getterOrOptions</span><br><span class="line">        setter = fn</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        getter = getterOrOptions.<span class="property">get</span>;</span><br><span class="line">        setter = getterOrOptions.<span class="property">set</span>  || fn</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">ComputedRefImpl</span>(getter,setter)</span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">ComputedRefImpl</span>&#123;</span><br><span class="line">    <span class="keyword">private</span> _value;</span><br><span class="line">    <span class="keyword">private</span> _dirty = <span class="literal">true</span>;</span><br><span class="line">    <span class="keyword">public</span> effect;</span><br><span class="line">    <span class="keyword">public</span> deps;</span><br><span class="line">    <span class="title function_">constructor</span>(<span class="params">getter,<span class="keyword">public</span> setter</span>)&#123;</span><br><span class="line">        <span class="comment">// 拿到effect实例让函数执行</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// effect.deps 存的是属性对应的set集合</span></span><br><span class="line">       <span class="variable language_">this</span>.<span class="property">effect</span> = <span class="keyword">new</span> <span class="title class_">ReactiveEffect</span>(getter,<span class="function">()=&gt;</span>&#123;</span><br><span class="line">           <span class="keyword">if</span>(!<span class="variable language_">this</span>.<span class="property">_dirty</span>)&#123;</span><br><span class="line">                <span class="variable language_">this</span>.<span class="property">_dirty</span> = <span class="literal">true</span>;</span><br><span class="line">                <span class="comment">// 通知自己收集的effect执行</span></span><br><span class="line">                <span class="title function_">triggerEffects</span>(<span class="variable language_">this</span>.<span class="property">deps</span>)</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">get</span> <span class="title function_">value</span>()&#123; <span class="comment">// 只有当.value 的时候 dirty为true就执行</span></span><br><span class="line">        <span class="keyword">if</span>(activeEffect)&#123;</span><br><span class="line">            <span class="comment">// 让计算属性做依赖收集</span></span><br><span class="line">            <span class="comment">// 计算属性 -》 effect  set = [effect]</span></span><br><span class="line">            <span class="title function_">trackEffects</span>(<span class="variable language_">this</span>.<span class="property">deps</span> ||( <span class="variable language_">this</span>.<span class="property">deps</span> = <span class="keyword">new</span> <span class="title class_">Set</span>()))</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span>(<span class="variable language_">this</span>.<span class="property">_dirty</span>)&#123;</span><br><span class="line">           <span class="variable language_">this</span>.<span class="property">_dirty</span> = <span class="literal">false</span></span><br><span class="line">           <span class="variable language_">this</span>.<span class="property">_value</span> = <span class="variable language_">this</span>.<span class="property">effect</span>.<span class="title function_">run</span>();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="property">_value</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">set</span> <span class="title function_">value</span>(<span class="params">newValues</span>)&#123;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="title function_">setter</span>(newValues)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><p>分支切换</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;IE=edge&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- &lt;script src=&quot;../../../node_modules/@vue/reactivity/dist/reactivity.global.js&quot;&gt;&lt;/script&gt; --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;./reactivity.global.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;app&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// 缓存代理结果 require()</span></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">const</span> &#123;effect ,reactive&#125; = <span class="title class_">VueReactivity</span>;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// 会对属性进行劫持 proxy， 监听用户的获取操作和设置操作</span></span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">const</span> state = <span class="title function_">reactive</span>(&#123; <span class="attr">flag</span>: <span class="literal">true</span>, <span class="attr">name</span>: <span class="string">&#x27;jw&#x27;</span>, <span class="attr">age</span>: <span class="number">30</span> &#125;)</span></span><br><span class="line"><span class="language-javascript">        <span class="title function_">effect</span>(<span class="function">() =&gt;</span> &#123; <span class="comment">// 副作用函数 (effect执行渲染了页面)</span></span></span><br><span class="line"><span class="language-javascript">            <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;render&#x27;</span>)</span></span><br><span class="line"><span class="language-javascript">            <span class="variable language_">document</span>.<span class="property">body</span>.<span class="property">innerHTML</span> = state.<span class="property">flag</span> ? state.<span class="property">name</span> : state.<span class="property">age</span></span></span><br><span class="line"><span class="language-javascript">        &#125;);</span></span><br><span class="line"><span class="language-javascript">        <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span></span><br><span class="line"><span class="language-javascript">            state.<span class="property">flag</span> = <span class="literal">false</span>;</span></span><br><span class="line"><span class="language-javascript">            <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span></span><br><span class="line"><span class="language-javascript">                <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;修改name，原则上不更新&#x27;</span>)</span></span><br><span class="line"><span class="language-javascript">                state.<span class="property">name</span> = <span class="string">&#x27;zf&#x27;</span></span></span><br><span class="line"><span class="language-javascript">            &#125;, <span class="number">1000</span>);</span></span><br><span class="line"><span class="language-javascript">        &#125;, <span class="number">1000</span>)</span></span><br><span class="line"><span class="language-javascript">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>停止依赖收集</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;IE=edge&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- &lt;script src=&quot;../../../node_modules/@vue/reactivity/dist/reactivity.global.js&quot;&gt;&lt;/script&gt; --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;./reactivity.global.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;app&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// 缓存代理结果 require()</span></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">const</span> &#123;effect ,reactive&#125; = <span class="title class_">VueReactivity</span>;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// 会对属性进行劫持 proxy， 监听用户的获取操作和设置操作</span></span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">const</span> state = <span class="title function_">reactive</span>(&#123; <span class="attr">flag</span>: <span class="literal">true</span>, <span class="attr">name</span>: <span class="string">&#x27;jw&#x27;</span>, <span class="attr">age</span>: <span class="number">30</span> &#125;)</span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// effect返回runner的目的是让用户可以自己控制渲染逻辑</span></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">const</span> runner = <span class="title function_">effect</span>(<span class="function">() =&gt;</span> &#123; <span class="comment">// 副作用函数 (effect执行渲染了页面)</span></span></span><br><span class="line"><span class="language-javascript">            <span class="variable language_">document</span>.<span class="property">body</span>.<span class="property">innerHTML</span> = state.<span class="property">flag</span> ? state.<span class="property">name</span> : state.<span class="property">age</span></span></span><br><span class="line"><span class="language-javascript">        &#125;);</span></span><br><span class="line"><span class="language-javascript">        runner.<span class="property">effect</span>.<span class="title function_">stop</span>();</span></span><br><span class="line"><span class="language-javascript">        <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span></span><br><span class="line"><span class="language-javascript">            state.<span class="property">flag</span> = <span class="literal">false</span>;</span></span><br><span class="line"><span class="language-javascript">            <span class="title function_">runner</span>()</span></span><br><span class="line"><span class="language-javascript">        &#125;, <span class="number">1000</span>)</span></span><br><span class="line"><span class="language-javascript">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>批量更新</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;IE=edge&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- &lt;script src=&quot;../../../node_modules/@vue/reactivity/dist/reactivity.global.js&quot;&gt;&lt;/script&gt; --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;./reactivity.global.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;app&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// 缓存代理结果 require()</span></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">const</span> &#123;effect ,reactive&#125; = <span class="title class_">VueReactivity</span>;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// 会对属性进行劫持 proxy， 监听用户的获取操作和设置操作</span></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">const</span> state = <span class="title function_">reactive</span>(&#123; <span class="attr">flag</span>: <span class="literal">true</span>, <span class="attr">name</span>: <span class="string">&#x27;jw&#x27;</span>, <span class="attr">age</span>: <span class="number">30</span>, <span class="attr">n</span>:&#123;<span class="attr">n</span>:<span class="number">100</span>&#125;&#125;)</span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// effect返回runner的目的是让用户可以自己控制渲染逻辑</span></span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">let</span> waiting = <span class="literal">false</span></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">const</span> runner = <span class="title function_">effect</span>(<span class="function">() =&gt;</span> &#123; <span class="comment">// 副作用函数 (effect执行渲染了页面)</span></span></span><br><span class="line"><span class="language-javascript">            <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;runner&#x27;</span>)</span></span><br><span class="line"><span class="language-javascript">            <span class="variable language_">document</span>.<span class="property">body</span>.<span class="property">innerHTML</span> = state.<span class="property">n</span>.<span class="property">n</span>;</span></span><br><span class="line"><span class="language-javascript">        &#125;,&#123;</span></span><br><span class="line"><span class="language-javascript">            <span class="title function_">scheduler</span>(<span class="params"></span>)&#123; <span class="comment">// 调度函数</span></span></span><br><span class="line"><span class="language-javascript">                <span class="keyword">if</span>(!waiting)&#123;</span></span><br><span class="line"><span class="language-javascript">                    waiting = <span class="literal">true</span></span></span><br><span class="line"><span class="language-javascript">                    <span class="title class_">Promise</span>.<span class="title function_">resolve</span>().<span class="title function_">then</span>(<span class="function">()=&gt;</span>&#123;</span></span><br><span class="line"><span class="language-javascript">                        <span class="title function_">runner</span>();</span></span><br><span class="line"><span class="language-javascript">                        waiting = <span class="literal">false</span>;</span></span><br><span class="line"><span class="language-javascript">                    &#125;)</span></span><br><span class="line"><span class="language-javascript">                &#125;</span></span><br><span class="line"><span class="language-javascript">            &#125;</span></span><br><span class="line"><span class="language-javascript">        &#125;);</span></span><br><span class="line"><span class="language-javascript">        <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span></span><br><span class="line"><span class="language-javascript">            state.<span class="property">n</span>.<span class="property">n</span> = <span class="number">2000</span>;</span></span><br><span class="line"><span class="language-javascript">        &#125;, <span class="number">1000</span>)</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>computed</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;IE=edge&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- &lt;script src=&quot;../../../node_modules/@vue/reactivity/dist/reactivity.global.js&quot;&gt;&lt;/script&gt; --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;./reactivity.global.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;app&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// 缓存代理结果 require()</span></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">const</span> &#123;effect ,reactive,computed&#125; = <span class="title class_">VueReactivity</span>;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">const</span> state = <span class="title function_">reactive</span>(&#123; <span class="attr">firstName</span>:<span class="string">&#x27;姜&#x27;</span> , <span class="attr">lastName</span>:<span class="string">&#x27;文&#x27;</span> &#125;);</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// vue2中想更新值  this.xxx = &#x27;&#x27;</span></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// let fullName = computed(()=&gt;&#123; // dirty 缓存的概念</span></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">//     console.log(&#x27;runner&#x27;)</span></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">//     return state.firstName + state.lastName</span></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// &#125;);</span></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">let</span> fullName = <span class="title function_">computed</span>(&#123;</span></span><br><span class="line"><span class="language-javascript">            <span class="title function_">get</span>(<span class="params"></span>)&#123;</span></span><br><span class="line"><span class="language-javascript">                <span class="keyword">return</span> state.<span class="property">firstName</span> + state.<span class="property">lastName</span></span></span><br><span class="line"><span class="language-javascript">            &#125;,</span></span><br><span class="line"><span class="language-javascript">            <span class="title function_">set</span>(<span class="params">value</span>)&#123;</span></span><br><span class="line"><span class="language-javascript">                state.<span class="property">lastName</span> = value</span></span><br><span class="line"><span class="language-javascript">            &#125;</span></span><br><span class="line"><span class="language-javascript">        &#125;)</span></span><br><span class="line"><span class="language-javascript">        fullName.<span class="property">value</span> = <span class="number">100</span>;</span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// 装箱</span></span></span><br><span class="line"><span class="language-javascript">        <span class="title function_">effect</span>(<span class="function">()=&gt;</span>&#123;</span></span><br><span class="line"><span class="language-javascript">            app.<span class="property">innerHTML</span> = fullName.<span class="property">value</span></span></span><br><span class="line"><span class="language-javascript">        &#125;)</span></span><br><span class="line"><span class="language-javascript">      </span></span><br><span class="line"><span class="language-javascript">        <span class="built_in">setTimeout</span>(<span class="function">()=&gt;</span>&#123;</span></span><br><span class="line"><span class="language-javascript">            state.<span class="property">firstName</span> = <span class="string">&#x27;x&#x27;</span></span></span><br><span class="line"><span class="language-javascript">        &#125;,<span class="number">1000</span>);</span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// 计算属性就是一个effect 当我取值的时候 会访问firsName，lastName的值，会让firstName和lastKName 来收集当前的computedEffect</span></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// 计算属性也可以收集effect</span></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">//  effect</span></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// effectComputed</span></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// proxy</span></span></span><br><span class="line"><span class="language-javascript">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure></li>
</ul>

      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/wieldy/bailment-blog/2022/03/29/vue3-1.reactivity/" data-id="cljmgj1f0000pzc9jhnk8ce5q" data-title="1.reactivity" class="article-share-link">Share</a>
      
      
      
    </footer>
  </div>
  
</article>



  


  <nav id="page-nav">
    
    <a class="extend prev" rel="prev" href="/bailment-blog/page/2/">&laquo; Prev</a><a class="page-number" href="/bailment-blog/">1</a><a class="page-number" href="/bailment-blog/page/2/">2</a><span class="page-number current">3</span>
  </nav>

</section>
        
          <aside id="sidebar">
  
    

  
    

  
    
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2023/07/">July 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2023/06/">June 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2023/04/">April 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2023/03/">March 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2022/03/">March 2022</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/bailment-blog/2023/07/03/%E5%B7%A5%E4%BD%9C%E6%97%A5%E5%BF%97/">工作日志</a>
          </li>
        
          <li>
            <a href="/bailment-blog/2023/06/29/payMent/">payMent</a>
          </li>
        
          <li>
            <a href="/bailment-blog/2023/06/20/%E7%BD%91%E7%BA%A2%E9%9D%A2%E8%AF%95%E9%A2%98/">原理题</a>
          </li>
        
          <li>
            <a href="/bailment-blog/2023/06/19/%E5%89%8D%E7%AB%AF%E5%A4%A7%E5%B1%8F%E8%87%AA%E9%80%82%E5%BA%94%E6%96%B9%E6%B3%95/">前端大屏自适应方法</a>
          </li>
        
          <li>
            <a href="/bailment-blog/2023/06/17/10%E4%B8%AAJavaScript%E5%B8%B8%E8%A7%81%E9%AB%98%E7%BA%A7%E7%9F%A5%E8%AF%86%E7%82%B9/">10个JavaScript常见高级知识点</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      
      &copy; 2023 John Doe<br>
      Powered by <a href="https://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>

    </div>
    <nav id="mobile-nav">
  
    <a href="/bailment-blog/" class="mobile-nav-link">Home</a>
  
    <a href="/bailment-blog/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    


<script src="/bailment-blog/js/jquery-3.4.1.min.js"></script>



  
<script src="/bailment-blog/fancybox/jquery.fancybox.min.js"></script>




<script src="/bailment-blog/js/script.js"></script>





  </div>
</body>
</html>